Files
campus_spider/app/core/database.py
T
2026-07-24 18:08:13 +08:00

51 lines
1.4 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""MySQL 业务库数据源(同步)"""
from typing import Optional
from sqlalchemy import Engine, create_engine
from sqlalchemy.orm import DeclarativeBase, Session, sessionmaker
from app.config import settings
from app.core.logger import log
# ──────────── 内部变量 ────────────
_mysql_engine: Optional[Engine] = None
_mysql_session_factory: Optional[sessionmaker[Session]] = None
class MysqlBase(DeclarativeBase):
"""MySQL ORM 声明基类"""
pass
def init_db() -> None:
"""初始化 MySQL 数据源"""
global _mysql_engine, _mysql_session_factory
_mysql_engine = create_engine(
settings.mysql_url,
pool_size=settings.mysql_pool_size,
max_overflow=settings.mysql_max_overflow,
pool_timeout=settings.db_pool_timeout,
pool_recycle=3600,
pool_pre_ping=True,
echo=False,
)
_mysql_session_factory = sessionmaker(_mysql_engine, expire_on_commit=False)
log.info("MySQL 数据源初始化完成: {}", settings.db_host)
def close_db() -> None:
"""关闭 MySQL 数据源"""
if _mysql_engine:
_mysql_engine.dispose()
log.info("MySQL 数据源已关闭")
def MysqlSession() -> Session:
"""获取 MySQL 会话(用作 with MysqlSession() as session"""
if _mysql_session_factory is None:
raise RuntimeError("数据库未初始化,请先调用 init_db()")
return _mysql_session_factory()