| 1234567891011121314151617181920212223242526272829303132333435363738394041 |
- from sqlalchemy.ext.asyncio import (
- create_async_engine,
- async_sessionmaker,
- AsyncSession,
- )
- from sqlalchemy.orm import declarative_base
- from app.core.config import settings
- # =========================
- # Async Engine
- # =========================
- engine = create_async_engine(
- settings.database_url, # ⚠️ 必须是 async URL
- echo=settings.debug,
- pool_pre_ping=True,
- pool_recycle=1800,
- )
- # =========================
- # Async Session 工厂
- # =========================
- AsyncSessionLocal = async_sessionmaker(
- bind=engine,
- class_=AsyncSession,
- autoflush=False,
- expire_on_commit=False,
- )
- # ORM 基类
- Base = declarative_base()
- # =========================
- # FastAPI 依赖
- # =========================
- async def get_db() -> AsyncSession:
- async with AsyncSessionLocal() as session:
- try:
- yield session
- finally:
- await session.close()
|