Engine, session, get_db dependency
Setup# pip install sqlalchemy asyncpg (postgres) / aiosqlite (sqlite)
from sqlalchemy.ext.asyncio import create_async_engine, async_sessionmaker
from sqlalchemy.orm import DeclarativeBase
DATABASE_URL = "postgresql+asyncpg://user:pass@localhost/mydb"
# DEV: "sqlite+aiosqlite:///./dev.db"
engine = create_async_engine(
DATABASE_URL, pool_size=10, max_overflow=20, pool_recycle=3600
)
SessionLocal = async_sessionmaker(engine, expire_on_commit=False)
class Base(DeclarativeBase): pass
async def get_db():
async with SessionLocal() as session:
try:
yield session
await session.commit()
except Exception:
await session.rollback()
raiseWatch out: Name the factory SessionLocal, not AsyncSession - that name belongs to SQLAlchemy's session class, and shadowing it breaks type hints like db: AsyncSession.