SQLAlchemy, need help understanding scoped_session

Viewed 170

Given the following setup, with the intention of using SQLAlchemy in FastAPI (with asyncio):

# db.py

from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine
from sqlalchemy.orm import registry, scoped_session, sessionmaker

engine = create_async_engine(url)
SessionMaker = sessionmaker(bind=engine, expire_on_commit=False, class_=AsyncSession)
session = scoped_session(SessionMaker)
mapper_registry = registry()

What is the correct way to use session here?

I noticed that you can use session directly:

from db import session

stmt = select(User)
res = session.execute(stmt).filter_by(uuid=uuid)

user = res.scalars().first()

Or you can use the context manager, like this:


from db import session

async with session() as sess:
    stmt = select(User)
    res = session.execute(stmt).filter_by(uuid=uuid)

    user = res.scalars().first()

What is more correct? In the context of a request in FastAPI, is it better to "create" a new session for each request? Or can you used db.session directly? What is the difference?

0 Answers
Related