Application runs with uvicorn but can't find Module (No module named 'app')

Question:

.
├── __pycache__
│   └── api.cpython-310.pyc
├── app
│   ├── __pycache__
│   │   └── main.cpython-310.pyc
│   ├── api_v1
│   │   ├── __pycache__
│   │   │   └── apis.cpython-310.pyc
│   │   ├── apis.py
│   │   └── endpoints
│   │       ├── __pycache__
│   │       │   └── message_prediction.cpython-310.pyc
│   │       └── message_prediction.py
│   ├── config.py
│   ├── main.py
│   └── schemas
│       ├── Messages.py
│       └── __pycache__
│           └── Messages.cpython-310.pyc
├── app.egg-info
│   ├── PKG-INFO
│   ├── SOURCES.txt
│   ├── dependency_links.txt
│   └── top_level.txt
├── build
│   └── bdist.macosx-12.0-arm64
├── data
│   ├── processed
│   │   ├── offers_big.csv_cleaned.xlsx
│   │   └── requests_big.csv_cleaned.xlsx
│   ├── processed.dvc
│   ├── raw
│   │   ├── offers.csv.old
│   │   ├── offers_big.csv
│   │   ├── requests.csv.old
│   │   └── requests_big.csv
│   ├── raw.dvc
│   ├── validated
│   │   ├── validated_offers.xlsx
│   │   └── validated_requests.xlsx
│   └── validated.dvc
├── dist
│   └── app-0.1.0-py3.10.egg
├── model.pkl
├── model.py
├── notebooks
│   └── contact-form.ipynb
├── requirements.in
├── requirements.txt
├── setup.py
└── test_api.py
# main.py
import os
from fastapi import FastAPI
import uvicorn
from app.api_v1.apis import api_router

# create the app
messages_classification_app = FastAPI()

messages_classification_app.include_router(api_router)

if __name__ == '__main__':
    uvicorn.run("app.main:messages_classification_app", host=os.getenv("HOST", "0.0.0.0"), port=int(os.getenv("PORT", 8000)))
# requirements.in
fastapi
uvicorn
-e file:.#egg=app

Trying to run the fastAPI app with python, results in error:

 py[learning]  ~/r/v/contact-form-classification   master ±  python app/main.py
Traceback (most recent call last):
  File "/Users/xxxxx/repos/visable/contact-form-classification/app/main.py", line 4, in <module>
    from app.api_v1.apis import api_router
ModuleNotFoundError: No module named 'app'

Running it with uvicorn directly works:

 py[learning]  ~/r/v/contact-form-classification   master ±  uvicorn app.main:messages_classification_app
INFO:     Started server process [53665]
INFO:     Waiting for application startup.
INFO:     Application startup complete.
INFO:     Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)

Any idea why? Looked into similar questions, don’t seem to apply to mine.

Asked By: George Katsanos

||

Answers:

python app/main.py will make app/ the first entry in sys.path, so app imports within won’t work.

Do python -m app.main to run app/main.py as a module without having Python touch sys.path.

Answered By: AKX
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.