Trung BìnhFastAPI iconFastAPI

FastAPI tích hợp SQL database nên quản lý session thế nào?

Mỗi request nên có session scope riêng, thường tạo bằng dependency yield. Service/repository nhận session qua dependency hoặc qua function parameter, commit/rollback ở layer rõ ràng.

Ví dụ:

python
async def get_db():
    async with SessionLocal() as session:
        yield session

@app.post("/users")
async def create_user(db: Annotated[AsyncSession, Depends(get_db)]):
    ...

Tránh global session dùng chung nhiều request.

Với SQLAlchemy async, cần dùng async engine/driver tương ứng như asyncpg cho PostgreSQL.

Xem toàn bộ FastAPI cùng filter theo level & chủ đề con.

Mở danh sách FastAPI