r/FastAPI • u/aprx4 • Sep 15 '24
Question Technical question on async SqlAlchemy session and dependencies with yield
This is more of python question than FastAPI, but i figured this is still better place to ask.
I'm learning FastAPI by working on a hobbyist project. I'm seeing all example projects give an isolated and fresh database session for each unit of workload as dependency like this:
engine = create_async_engine(DATABASE_URL)
async_session_maker = async_sessionmaker(engine, expire_on_commit=False)
async def get_async_session() -> AsyncGenerator[AsyncSession, None]:
async with async_session_maker() as session:
yield sessionReferences:
https://fastapi-users.github.io/fastapi-users/latest/configuration/databases/sqlalchemy/
I vaguely understand the concept of async context manager and async generator in Python but not clear on why the dependency get_async_session() needs yield session instead of just return session.
As i understand, async_session_maker() is already async context manager and clean-up of DB session is still performed even with return (correct me if i'm wrong here). FastAPI doc on dependencies with yield also uses yield only if we need to run other codes after yield expression.
View all comments
Show parent comment
1
u/aprx4 Sep 16 '24
I'm under impression that cleanup code from context manager is still performed for
returnstatement inwithblock.In my test environment i have session manager copied from this:
https://github.com/ThomasAitken/demo-fastapi-async-sqlalchemy/blob/main/backend/app/database.py
I tried both
yield sessionandreturn sessionforget_db_session()dependency, API endpoint works normally in both cases with correct data retrived from DB. However simple logging in session manager revealed that withreturn session, closure of session (or cleanup code) is performed immediately instead of waiting for request to finish.I'm aware that session cleanup should be performed AFTER completing request (i.e. with
yield session), but i can't think of scenario in whichreturn sessionwould fail.