database.py 925 B

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. from sqlalchemy.ext.asyncio import (
  2. create_async_engine,
  3. async_sessionmaker,
  4. AsyncSession,
  5. )
  6. from sqlalchemy.orm import declarative_base
  7. from app.core.config import settings
  8. # =========================
  9. # Async Engine
  10. # =========================
  11. engine = create_async_engine(
  12. settings.database_url, # ⚠️ 必须是 async URL
  13. echo=settings.debug,
  14. pool_pre_ping=True,
  15. pool_recycle=1800,
  16. )
  17. # =========================
  18. # Async Session 工厂
  19. # =========================
  20. AsyncSessionLocal = async_sessionmaker(
  21. bind=engine,
  22. class_=AsyncSession,
  23. autoflush=False,
  24. expire_on_commit=False,
  25. )
  26. # ORM 基类
  27. Base = declarative_base()
  28. # =========================
  29. # FastAPI 依赖
  30. # =========================
  31. async def get_db() -> AsyncSession:
  32. async with AsyncSessionLocal() as session:
  33. try:
  34. yield session
  35. finally:
  36. await session.close()