Files
site/apps/api/app/modules/zootech/wesp_bridge_db.py
T
2026-07-17 12:57:18 +03:00

43 lines
1.1 KiB
Python

"""Thread-local DB session bridge for ported WESP services."""
from __future__ import annotations
from contextlib import contextmanager
from contextvars import ContextVar
from typing import Iterator
from sqlalchemy.orm import Session
_current_session: ContextVar[Session | None] = ContextVar("wesp_current_session", default=None)
class _WespDB:
@property
def session(self) -> Session:
db = _current_session.get()
if db is None:
raise RuntimeError("wesp_bridge_db: no active session — use wesp_db_session()")
return db
db = _WespDB()
@contextmanager
def wesp_db_session(existing: Session | None = None) -> Iterator[Session]:
if existing is not None:
token = _current_session.set(existing)
try:
yield existing
finally:
_current_session.reset(token)
return
from app.core.database import session_scope
with session_scope() as session:
token = _current_session.set(session)
try:
yield session
finally:
_current_session.reset(token)