"""数据库会话依赖""" from typing import AsyncGenerator from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine, async_sessionmaker from app.config import settings # 处理 sqlite 协议兼容 db_url = settings.DATABASE_URL if db_url.startswith("sqlite"): db_url = db_url.replace("sqlite://", "sqlite+aiosqlite://") engine = create_async_engine(db_url, echo=False, pool_pre_ping=True) async_session = async_sessionmaker(engine, class_=AsyncSession, expire_on_commit=False) async def get_db() -> AsyncGenerator[AsyncSession, None]: async with async_session() as session: try: yield session finally: await session.close() async def init_db(): """创建所有表""" from app.models.device import Base async with engine.begin() as conn: await conn.run_sync(Base.metadata.create_all)