What is AsyncSession in SQLAlchemy and what are the rules for working with it in the context of a FastAPI microservice?
sobes.tech AI
Answer from AI
AsyncSession in SQLAlchemy is an asynchronous version of the session for working with the database, allowing input-output operations (such as database queries) to be performed without blocking the main thread. In the context of a FastAPI microservice, this is especially important for improving performance and scalability.
Main rules for working with AsyncSession in FastAPI:
-
Creating a session: Usually, AsyncSession is created via
async_sessionmaker, which is configured for an asynchronous engine (for example, usingasyncpgfor PostgreSQL). -
Lifecycle of the session: In FastAPI, it is recommended to use a dependency with
yieldto create the session during request processing and close it properly afterward. -
Asynchronous operations: All database operations (queries, commits) should be performed using
await. -
Transactions: You can use the context manager
async with session.begin():for automatic transaction management.
Example of a dependency for AsyncSession in FastAPI:
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
from fastapi import Depends
DATABASE_URL = "postgresql+asyncpg://user:password@localhost/dbname"
engine = create_async_engine(DATABASE_URL, echo=True)
async_session = async_sessionmaker(engine, expire_on_commit=False)
async def get_async_session() -> AsyncSession:
async with async_session() as session:
yield session
In FastAPI handlers, you can accept a session as follows:
from fastapi import APIRouter, Depends
router = APIRouter()
@router.get("/items/")
async def read_items(session: AsyncSession = Depends(get_async_session)):
result = await session.execute("SELECT * FROM items")
items = result.scalars().all()
return items
Thus, AsyncSession provides non-blocking database operations, which is important for asynchronous web applications on FastAPI.