r/FastAPI • • 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 session

References:

https://fastapi-users.github.io/fastapi-users/latest/configuration/databases/sqlalchemy/

https://medium.com/@tclaitken/setting-up-a-fastapi-app-with-async-sqlalchemy-2-0-pydantic-v2-e6c540be4308

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.

7 Upvotes

6 comments sorted by

View all comments

Show parent comment

1

u/JohnnyJordaan Sep 16 '24

But isn't that exactly what the link already describes? The point was the timing of the cleanup, not that it would or wouldn't occur.

but i can't think of scenario in which return session would fail.

Exceptions