[Python] How to do persistent database connection in FastAPI?

Discussão em 'Python' iniciado por Stack, Fevereiro 15, 2025.

  1. Stack

    Stack Membro Participativo

    I am writing my first project in FastAPI and I am struggling a bit. In particular, I am not sure how I am supposed to use asyncpg connection pool in my app. Currently what I have goes like this

    in db.py I have

    pgpool = None


    async def get_pool():
    global pgpool
    if not pgpool:
    pgpool = await asyncpg.create_pool(dsn='MYDB_DSN')
    return pgpool


    and then in individual files I use the get_pool as a dependency.

    @router.post("/user/", response_model=models.User, status_code=201)
    async def create_user(user: models.UserCreate, pgpool = Depends(get_pool)):
    # ... do things ...


    First, every endpoint I have uses the database, so it seems silly to add that dependency argument for every single function. Second, this seems like a roundabout way of doing things. I define a global, then I define a function that returns that global and then I inject the function. I am sure there is more natural way of going about it.

    I have seen people suggest just adding whatever I need as a property to the app object

    @app.on_event("startup")
    async def startup():
    app.pool = await asyncpg.create_pool(dsn='MYDB_DSN')


    but it doesn't work when I have multiple files with routers, I don't know how to access the app object from a router object.

    What am I missing?

    Continue reading...

Compartilhe esta Página