Skip to content

Commit

Permalink
fix: attempt at using a context manager, no joy
Browse files Browse the repository at this point in the history
Generated-by: aiautocommit
  • Loading branch information
iloveitaly committed Jan 14, 2025
1 parent 2dbb57a commit 409ed6d
Showing 1 changed file with 9 additions and 8 deletions.
17 changes: 9 additions & 8 deletions activemodel/session_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
"""

import contextlib
import contextvars
import json
import typing as t

Expand Down Expand Up @@ -44,8 +45,6 @@ class SessionManager:
session_connection: Connection | None
"optionally specify a specific session connection to use for all get_session() calls, useful for testing"

session: Session | None

@classmethod
def get_instance(cls, database_url: str | None = None) -> "SessionManager":
if cls._instance is None:
Expand All @@ -61,7 +60,6 @@ def __init__(self, database_url: str):
self._engine = None

self.session_connection = None
self.session = None

# TODO why is this type not reimported?
def get_engine(self) -> Engine:
Expand All @@ -78,12 +76,11 @@ def get_engine(self) -> Engine:
return self._engine

def get_session(self):
if self.session:
if self._session_context:

@contextlib.contextmanager
def _fake():
assert self.session
yield self.session
yield self._session_context.get()

return _fake()

Expand All @@ -99,14 +96,18 @@ def global_session(self):
`session_connection`, restoring it to `None` at the end.
"""

self._session_context = contextvars.ContextVar[Session | None](
"session_context", default=None
)

# Generate a new connection and set it as the session_connection
with self.get_session() as session:
self.session = session
token = self._session_context.set(session)

try:
yield
finally:
self.session = None
self._session_context.reset(token)


def init(database_url: str):
Expand Down

0 comments on commit 409ed6d

Please sign in to comment.