hot_content_mysql.py 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. from collections.abc import Generator
  2. from sqlalchemy import create_engine, text
  3. from sqlalchemy.engine import Engine
  4. from sqlalchemy.orm import Session, sessionmaker
  5. from app.core.config import settings
  6. _hot_content_engine: Engine | None = None
  7. _hot_content_session_local: sessionmaker[Session] | None = None
  8. def _ensure_hot_content_engine() -> sessionmaker[Session]:
  9. global _hot_content_engine, _hot_content_session_local
  10. if not settings.hot_content_mysql_configured:
  11. raise RuntimeError(
  12. "新热内容库未配置,请在 .env 中设置 HOT_CONTENT_MYSQL_HOST、"
  13. "HOT_CONTENT_MYSQL_USER、HOT_CONTENT_MYSQL_PASSWORD、HOT_CONTENT_MYSQL_DATABASE"
  14. )
  15. if _hot_content_session_local is None:
  16. _hot_content_engine = create_engine(
  17. settings.hot_content_mysql_dsn,
  18. pool_pre_ping=True,
  19. pool_recycle=3600,
  20. )
  21. _hot_content_session_local = sessionmaker(
  22. bind=_hot_content_engine,
  23. autoflush=False,
  24. autocommit=False,
  25. )
  26. return _hot_content_session_local
  27. def HotContentSessionLocal() -> Session:
  28. """打开新热内容库会话(独立 MySQL,用法同 SessionLocal())。"""
  29. return _ensure_hot_content_engine()()
  30. def get_hot_content_db_session() -> Generator[Session, None, None]:
  31. db = HotContentSessionLocal()
  32. try:
  33. yield db
  34. finally:
  35. db.close()
  36. def hot_content_mysql_ping() -> bool:
  37. _ensure_hot_content_engine()
  38. assert _hot_content_engine is not None
  39. with _hot_content_engine.connect() as conn:
  40. conn.execute(text("SELECT 1"))
  41. return True