| 12345678910111213141516171819202122232425262728293031323334353637383940 |
- from sqlalchemy import create_engine
- from sqlalchemy.orm import sessionmaker, declarative_base
- from app.core.config import settings
- # =========================
- # 数据库初始化
- # =========================
- # 建立 Engine
- engine = create_engine(
- settings.database_url,
- echo=settings.debug, # 是否打印 SQL 日志
- pool_pre_ping=True, # 检测断开的连接
- pool_recycle=1800, # 连接回收时间,防止 MySQL 8 小时断开
- future=True # 启用 SQLAlchemy 2.0 风格
- )
- # 建立 Session 工厂
- SessionLocal = sessionmaker(
- autocommit=False,
- autoflush=False,
- bind=engine,
- expire_on_commit=False
- )
- # ORM 基类
- Base = declarative_base()
- # =========================
- # 数据库依赖
- # =========================
- def get_db():
- """
- FastAPI 的依赖注入函数,用于在请求周期内创建并关闭数据库会话。
- """
- db = SessionLocal()
- try:
- yield db
- finally:
- db.close()
|