database.py 1003 B

12345678910111213141516171819202122232425262728293031323334353637383940
  1. from sqlalchemy import create_engine
  2. from sqlalchemy.orm import sessionmaker, declarative_base
  3. from app.core.config import settings
  4. # =========================
  5. # 数据库初始化
  6. # =========================
  7. # 建立 Engine
  8. engine = create_engine(
  9. settings.database_url,
  10. echo=settings.debug, # 是否打印 SQL 日志
  11. pool_pre_ping=True, # 检测断开的连接
  12. pool_recycle=1800, # 连接回收时间,防止 MySQL 8 小时断开
  13. future=True # 启用 SQLAlchemy 2.0 风格
  14. )
  15. # 建立 Session 工厂
  16. SessionLocal = sessionmaker(
  17. autocommit=False,
  18. autoflush=False,
  19. bind=engine,
  20. expire_on_commit=False
  21. )
  22. # ORM 基类
  23. Base = declarative_base()
  24. # =========================
  25. # 数据库依赖
  26. # =========================
  27. def get_db():
  28. """
  29. FastAPI 的依赖注入函数,用于在请求周期内创建并关闭数据库会话。
  30. """
  31. db = SessionLocal()
  32. try:
  33. yield db
  34. finally:
  35. db.close()