database.py 805 B

12345678910111213141516171819202122
  1. from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine, async_sessionmaker
  2. from app.config import settings
  3. # 创建异步数据库引擎
  4. engine = create_async_engine(settings.database_url, echo=False)
  5. # 异步 Session 工厂
  6. async_session = async_sessionmaker(engine, class_=AsyncSession, expire_on_commit=False)
  7. async def get_db():
  8. """FastAPI 依赖注入,提供数据库 Session"""
  9. async with async_session() as session:
  10. yield session
  11. async def create_tables():
  12. """开发环境:通过 SQLAlchemy 直接建表(生产环境请使用 SQL 迁移文件)"""
  13. from app.models import Base
  14. from app.models import domain, visitor, monitoring, license # noqa: F401
  15. async with engine.begin() as conn:
  16. await conn.run_sync(Base.metadata.create_all)