Start Uvicorn with fastapi having main.py and app.py

1k views Asked by At

I was making an authentication backend with Fastapi following the user's guide and don't know how to start a server now.

Files and folders of the project structure are the following:

<project_name>/
    main.py
    app/
        app.py

The content of the main.py script:

import uvicorn

if __name__ == "__main__":
    uvicorn.run("app.app:app", host="0.0.0.0", log_level="info")

The content of the app/app.py script:

from fastapi import Depends, FastAPI

from app.db import User, create_db_and_tables
from app.schemas import UserCreate, UserRead, UserUpdate
from app.users import auth_backend, current_active_user, fastapi_users

app = FastAPI()

# Rest of the code...

And when I'm trying to start a server with the command from my <project_name>/ folder:

uvicorn main:app --reload

It gives me this error message:

ERROR: Error loading ASGI app. Attribute "app" not found in module "main".

How to start the server in this case?

4

There are 4 answers

0
yunchi On BEST ANSWER

try running uvicorn app.app:app from <project_name>/ (don't think your main.py is necessary)

2
Kostas Nitaf On

You should run uvicorn app:app --reload from <project_name>/app/

0
Syed Rafay On

You can make sub-applications and then register them in your main.py (main application) like this:

# app/app.py

from fastapi import FastAPI

app = FastAPI()


@app.get("/")
async def root():
    return {"message": "Hello World"}
# main.py

import uvicorn
from fastapi import FastAPI

from app.app import app

mainApp = FastAPI()
mainApp.mount("/app", app)  # your app routes will now be /app/{your-route-here}


if __name__ == "__main__":
    uvicorn.run(mainApp, host="0.0.0.0", log_level="info")

Now run your main application like this:

uvicorn main:mainApp --reload

Keep in mind that above example mounts your sub-application at /app, you your hello world route becomes http://127.0.0.1:8000/app/. You can do mainApp.mount("/", app) to mount your sub-application at root and then your hello world route becomes http://127.0.0.1:8000/.

Read more about Sub Applications here https://fastapi.tiangolo.com/advanced/sub-applications/

0
KIRAN KUMAR N On

when running the Uvicorn server, execute it from the directory containing the main.py file