from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine, async_sessionmaker from sqlalchemy.orm import declarative_base from .settings import get_settings settings = get_settings() DATABASE_URL = ( f"mysql+aiomysql://{settings.DB_USER}:{settings.DB_PASSWORD}" f"@{settings.DB_HOST}:{settings.DB_PORT}/{settings.DB_NAME}" f"?charset={settings.DB_CHARSET}" ) engine = create_async_engine(DATABASE_URL, echo=settings.DEBUG, future=True) AsyncSessionLocal = async_sessionmaker( engine, class_=AsyncSession, expire_on_commit=False ) Base = declarative_base() async def get_db(): """获取数据库会话的依赖项函数 用于FastAPI依赖注入,自动管理数据库会话的生命周期 成功时自动提交,异常时自动回滚,最后确保关闭会话 """ async with AsyncSessionLocal() as session: try: yield session await session.commit() except Exception: await session.rollback() raise finally: await session.close() async def init_db(): """初始化数据库,创建所有表结构""" async with engine.begin() as conn: await conn.run_sync(Base.metadata.create_all)