Michael Kremenetsky
Michael Kremenetsky

Reputation: 129

ModuleNotFoundError: No module named 'app.routes'

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

Answers (4)

Andre Goulart
Andre Goulart

Reputation: 596

Based on https://github.com/tiangolo/fastapi/issues/3602, you just need to work at a higher level of your project.

3 Alternative solutions:

myproject/
└── app/
    ├── main.py
    ├── __init__.py
    └── utils/
        ├── tools.py
        └── __init__.py

1. Use the full path (or relative path) on import

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.

2. Use an auxiliar file at the top level:

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

3. Make sure you are at the right path:

Didn't work for me

Simply cd to this level will probably solve.

cd myproject/
uvicorn app.main:app --reload

Upvotes: 1

namitha gowda
namitha gowda

Reputation: 111

Just run below command

export PYTHONPATH=$PWD

Upvotes: 7

Michael Kremenetsky
Michael Kremenetsky

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

Teejay Bruno
Teejay Bruno

Reputation: 2159

Your uvicorn command is slightly off. From whatever directory is above app run --

uvicorn app.main:app --reload

Upvotes: 9

Related Questions