36 lines
856 B
Python
36 lines
856 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()
|
|
|
|
# 注意:本服务不自动建表。
|
|
# 数据库结构由 docs/schema.sql 手动初始化(与 models.py 保持同步维护)。
|