[Python] How to initialize db connection in FastAPI with lifespan events? [duplicate]

Discussão em 'Python' iniciado por Stack, Maio 16, 2025.

  1. Stack

    Stack Membro Participativo

    I would like to initialize a DB connection for my FastAPI application and tried to follow the tutorial for Lifespan Events.

    I set up a lifecycle function and plugged it into my app and within the function, the variable is initialized but after the start up, the variable remains None.

    db_session = None


    @asynccontextmanager
    async def lifespan(app: FastAPI):
    db_session = DBConnection("file.db")
    if db_session.get_db_connection() is None:
    raise InitializationError("Could not get access database file.")
    print(db_session.get_test_value()) # Prints out a valid value
    yield

    app = FastAPI(lifespan=lifespan)
    app.mount("/static", StaticFiles(directory="static"), name="static")
    templates = Jinja2Templates(directory="templates")
    print(db_session) # Prints None

    Versions

    • Python 3.9
    • FastAPI 0.114.2
    • Pydantic 2.9.1
    • uvicorn 0.30.6
    What I tried


    I initialized the value with [] instead of None.

    I initialized the value with {} instead of None (like in the tutorial).

    I plugged the db session into `db_session["db"] instead of assigning it directly, the map remains empty.

    I initialized the value in lifespan with a string, just to test.

    I declared the variable db_session as global in the lifespan function before assigning it the value.

    All tests lead to the same result, that the value is as initialized outside of the lifespanfunction (None or [] or {}).

    The error persists during the handling of the requests.

    Continue reading...

Compartilhe esta Página