Reputation: 129
So I'm learning fastapi right now and I was trying to separate my project into multiple files but when I do I get this error.
ModuleNotFoundError: No module named 'app.routes'
I have read This multiple times and I'm pretty sure I did everything right can anyone tell me what I did wrong?
app
│ main.py
│ __init__.py
│
└───routes
auth.py
__init__.py
main.py
from fastapi import FastAPI
from app.routes import auth
app = FastAPI()
app.include_router(auth.router)
auth.py
from fastapi import APIRouter
router = APIRouter()
@router.get("/test")
async def test():
return {"test": "test"}
I ran uvicorn main:app --reload
Upvotes: 9
Views: 19143
Reputation: 596
Based on https://github.com/tiangolo/fastapi/issues/3602, you just need to work at a higher level of your project.
myproject/
└── app/
├── main.py
├── __init__.py
└── utils/
├── tools.py
└── __init__.py
✅ import .utils.tools
relative import works, but we should avoid that.
❌ import utils.tools
doesn't work.
❌ import app.utils.tools
neither.
✅ import myproject.app.utils.tools
works fine for me.
Add a simple proxy file at the same level of your app
folder:
#run.py
from app.main import app
myproject/
├── app/
│ ├── main.py
│ └── utils/
│ ├── tools.py
│ └── __init__.py
└── run.py
And run:
uvicorn run:app --reload
Didn't work for me
Simply cd
to this level will probably solve.
cd myproject/
uvicorn app.main:app --reload
Upvotes: 1
Reputation: 129
Ok, I asked on github and I they were able to fix it. Post: https://github.com/tiangolo/fastapi/issues/3602
Upvotes: 1
Reputation: 2159
Your uvicorn command is slightly off. From whatever directory is above app
run --
uvicorn app.main:app --reload
Upvotes: 9