блоки 2 и 3 доработки интерфейса системы тестирования

This commit is contained in:
Константин Лебединский
2026-04-29 21:06:17 +05:00
parent eff3fda5b0
commit bba96f8f9f
37 changed files with 4440 additions and 1292 deletions
+70 -74
View File
@@ -1,7 +1,7 @@
"""Подключение к PostgreSQL — тот же паттерн, что в HR_TG_Bot/tgFlaskForm/db/session.py.
"""Подключение к PostgreSQL и ORM-сессии.
В Этапе 1 работаем с БД `clinic_tests` (схема не меняется). Опционально доступна
вторая БД `hr_bot_test` для HR-аутентификации (см. .env.example, флаг HR_AUTH).
Основная БД `clinic_tests`.
Опциональная вторая БД `hr_bot_test` (когда HR_AUTH=1).
"""
from __future__ import annotations
@@ -11,76 +11,85 @@ from typing import Optional
from sqlalchemy import create_engine
from sqlalchemy.engine import Engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.orm import Session, scoped_session, sessionmaker
from sqlalchemy.pool import QueuePool
_lock = threading.Lock()
_engine: Optional[Engine] = None
_session_local: Optional[sessionmaker] = None
_hr_engine: Optional[Engine] = None
_hr_session_local: Optional[sessionmaker] = None
_engine_lock = threading.Lock()
_session_lock = threading.Lock()
_hr_engine_lock = threading.Lock()
_engine: Optional[Engine] = None
_session_factory: Optional[scoped_session] = None
_hr_engine: Optional[Engine] = None
# ─── URL helpers ─────────────────────────────────────────────────────────────
def get_database_url() -> str:
"""URL основной БД (`clinic_tests`).
Приоритет: DATABASE_URL → отдельные DB_*-переменные.
"""
if db_url := os.environ.get('DATABASE_URL'):
return db_url.strip()
db_host = os.environ.get('DB_HOST', 'localhost')
db_port = os.environ.get('DB_PORT', '5432')
db_name = os.environ.get('DB_NAME', 'clinic_tests')
db_user = os.environ.get('DB_USER', 'hr_bot_user')
db_password = os.environ.get('DB_PASSWORD', 'hrbot123')
return f'postgresql://{db_user}:{db_password}@{db_host}:{db_port}/{db_name}'
def get_hr_database_url() -> Optional[str]:
"""URL БД HR (`hr_bot_test`) — только если включён HR_AUTH."""
if not _hr_auth_enabled():
return None
if url := os.environ.get('HR_DATABASE_URL'):
return url.strip()
return None
host = os.environ.get('DB_HOST', 'localhost')
port = os.environ.get('DB_PORT', '5432')
name = os.environ.get('DB_NAME', 'clinic_tests')
user = os.environ.get('DB_USER', 'hr_bot_user')
password = os.environ.get('DB_PASSWORD', 'hrbot123')
return f'postgresql+psycopg2://{user}:{password}@{host}:{port}/{name}'
def _hr_auth_enabled() -> bool:
val = (os.environ.get('HR_AUTH') or '').strip().lower()
return val in ('1', 'true', 'yes', 'on')
return (os.environ.get('HR_AUTH') or '').strip().lower() in ('1', 'true', 'yes', 'on')
def get_hr_database_url() -> Optional[str]:
if not _hr_auth_enabled():
return None
url = (os.environ.get('HR_DATABASE_URL') or '').strip()
return url or None
# ─── Main engine ─────────────────────────────────────────────────────────────
def get_engine() -> Engine:
"""Возвращает общий engine основной БД (singleton на процесс)."""
global _engine
if _engine is not None:
return _engine
with _lock:
if _engine is not None:
return _engine
_engine = create_engine(
get_database_url(),
poolclass=QueuePool,
pool_size=5,
max_overflow=10,
pool_pre_ping=True,
)
with _engine_lock:
if _engine is None:
_engine = create_engine(
get_database_url(),
poolclass=QueuePool,
pool_size=5,
max_overflow=10,
pool_pre_ping=True,
)
return _engine
def get_session():
"""Создаёт новую ORM-сессию поверх общего engine."""
global _session_local
if _session_local is None:
with _lock:
if _session_local is None:
_session_local = sessionmaker(bind=get_engine())
return _session_local()
# ─── Scoped session ──────────────────────────────────────────────────────────
def get_session() -> Session:
"""Возвращает ORM-сессию для текущего потока (scoped_session)."""
global _session_factory
if _session_factory is None:
with _session_lock:
if _session_factory is None:
# Инициализируем engine до захвата session_lock, чтобы не было вложенных блокировок
engine = get_engine()
_session_factory = scoped_session(
sessionmaker(bind=engine, autoflush=True, autocommit=False)
)
return _session_factory # type: ignore[return-value]
def remove_session() -> None:
"""Освобождает сессию для текущего потока. Вызывается в teardown_appcontext."""
if _session_factory is not None:
_session_factory.remove()
# ─── HR engine (raw SQL only) ────────────────────────────────────────────────
def get_hr_engine() -> Optional[Engine]:
"""Engine для HR-БД. Возвращает None, если HR_AUTH не включён."""
if not _hr_auth_enabled():
return None
global _hr_engine
@@ -89,34 +98,21 @@ def get_hr_engine() -> Optional[Engine]:
url = get_hr_database_url()
if not url:
return None
with _lock:
if _hr_engine is not None:
return _hr_engine
_hr_engine = create_engine(
url,
poolclass=QueuePool,
pool_size=3,
max_overflow=5,
pool_pre_ping=True,
)
with _hr_engine_lock:
if _hr_engine is None:
_hr_engine = create_engine(
url,
poolclass=QueuePool,
pool_size=3,
max_overflow=5,
pool_pre_ping=True,
)
return _hr_engine
def get_hr_session():
"""Сессия для HR-БД (или None при выключенном HR_AUTH)."""
eng = get_hr_engine()
if eng is None:
return None
global _hr_session_local
if _hr_session_local is None:
with _lock:
if _hr_session_local is None:
_hr_session_local = sessionmaker(bind=eng)
return _hr_session_local()
# ─── Smoke check ─────────────────────────────────────────────────────────────
def ping() -> dict:
"""Smoke-проверка подключения к БД (используется в /health)."""
out: dict = {'main': 'unknown'}
try:
with get_engine().connect() as conn: