import os from sqlalchemy import create_engine from sqlalchemy.orm import declarative_base, sessionmaker # 优先读取环境变量(Docker 部署用);默认值与原硬编码配置一致,本地开发不受影响 MYSQL_USER = os.getenv("MYSQL_USER", "root") MYSQL_PASSWORD = os.getenv("MYSQL_PASSWORD", "123456") MYSQL_HOST = os.getenv("MYSQL_HOST", "localhost") MYSQL_PORT = os.getenv("MYSQL_PORT", "3306") MYSQL_DB = os.getenv("MYSQL_DB", "student_manager") db_url = f"mysql+pymysql://{MYSQL_USER}:{MYSQL_PASSWORD}@{MYSQL_HOST}:{MYSQL_PORT}/{MYSQL_DB}?charset=utf8mb4" engine = create_engine(db_url, pool_size=5, pool_pre_ping=True) Base = declarative_base() SessionLocal = sessionmaker(bind=engine) def get_db(): db = SessionLocal() try: yield db finally: db.close() def init_db(): """导入所有模型并建表,避免任何入口文件漏导入""" import model # noqa: F401 —— 触发 model/__init__.py 注册所有类 Base.metadata.create_all(bind=engine) def reset_db(): """开发环境重建所有表""" import model # noqa: F401 Base.metadata.drop_all(bind=engine) Base.metadata.create_all(bind=engine)