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ụ:
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.
Each request should have its own session scope, usually created with a yield dependency. Services/repositories receive the session through dependency injection or function parameters, and commit/rollback should happen in a clear layer.
Example:
async def get_db():
async with SessionLocal() as session:
yield session
@app.post("/users")
async def create_user(db: Annotated[AsyncSession, Depends(get_db)]):
...Avoid a global session shared by many requests.
With SQLAlchemy async, use the matching async engine/driver such as asyncpg for PostgreSQL.