1+ __all__ = ("get_current_session" , "session_context" , "require_active_session" )
2+
13import sys
2- from typing import TYPE_CHECKING , List , Dict , Any , Optional , TypeVar , Callable , Union
4+ from contextlib import contextmanager
5+ from contextvars import ContextVar , Token
6+ from typing import TYPE_CHECKING , Any , Callable , Dict , List , Optional , TypeVar , Union
37
48if TYPE_CHECKING :
59 from ._session import Session
@@ -16,10 +20,29 @@ class RenderedDeps(TypedDict):
1620 html : str
1721
1822
23+ # ==============================================================================
24+ # Context manager for current session (AKA current reactive domain)
25+ # ==============================================================================
26+ _current_session : ContextVar [Optional ["Session" ]] = ContextVar (
27+ "current_session" , default = None
28+ )
29+
30+
31+ def get_current_session () -> Optional ["Session" ]:
32+ return _current_session .get ()
33+
34+
35+ @contextmanager
36+ def session_context (session : Optional ["Session" ]):
37+ token : Token [Union [Session , None ]] = _current_session .set (session )
38+ try :
39+ yield
40+ finally :
41+ _current_session .reset (token )
42+
43+
1944def require_active_session (session : Optional ["Session" ]) -> "Session" :
2045 if session is None :
21- from ._session import get_current_session
22-
2346 session = get_current_session ()
2447 if session is None :
2548 import inspect
0 commit comments