39 lines
922 B
Python
39 lines
922 B
Python
"""
|
|
MySQL 数据库连接与 SQLAlchemy 引擎初始化
|
|
"""
|
|
from sqlalchemy import create_engine
|
|
from sqlalchemy.orm import sessionmaker, declarative_base
|
|
|
|
from .config import settings
|
|
|
|
# 连接池配置:避免频繁创建连接
|
|
engine = create_engine(
|
|
settings.DATABASE_URL,
|
|
pool_pre_ping=True,
|
|
pool_recycle=3600,
|
|
pool_size=10,
|
|
max_overflow=20,
|
|
echo=settings.DEBUG,
|
|
connect_args={"charset": "utf8mb4"},
|
|
)
|
|
|
|
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
|
|
|
|
# 所有 ORM 模型的基类
|
|
Base = declarative_base()
|
|
|
|
|
|
def get_db():
|
|
"""FastAPI 依赖注入:获取数据库会话"""
|
|
db = SessionLocal()
|
|
try:
|
|
yield db
|
|
finally:
|
|
db.close()
|
|
|
|
|
|
def init_db() -> None:
|
|
"""创建所有表(生产环境建议改用 Alembic 迁移)"""
|
|
from . import models # noqa: F401 确保模型被导入
|
|
Base.metadata.create_all(bind=engine)
|