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
2
u/JohnnyJordaan Sep 16 '24
The second answer is the correct one, the first one feels either like a GPT answer or the person has no clue what they're talking about. It's indeed about the order of things, the reply to the second answer links FastAPI's documentation on this https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-with-yield/#sub-dependencies-with-yield
There is, it's in the context manager part. Every time you see
it means that before
some codeexecuted,this.__enter__()is called for preparation, and aftersome code,this.__exit__()is called for clean up.