from __future__ import annotations from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine from app.core.config import get_settings def create_engine(): """ 创建异步 Engine。 注意:连接串从环境变量 `DATABASE_URL` 读取。 """ settings = get_settings() return create_async_engine(settings.database_url, pool_pre_ping=True) engine = create_engine() AsyncSessionLocal: async_sessionmaker[AsyncSession] = async_sessionmaker( bind=engine, expire_on_commit=False, autoflush=False, autocommit=False, ) async def get_db() -> AsyncSession: """ FastAPI 依赖:获取数据库会话。 """ async with AsyncSessionLocal() as session: yield session