Skip to content

Commit 33bd8f6

Browse files
author
Eugene Shershen
committed
init session
1 parent 70d4494 commit 33bd8f6

File tree

2 files changed

+12
-1
lines changed

2 files changed

+12
-1
lines changed

fastapi_async_sqlalchemy/middleware.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -67,11 +67,14 @@ def __init__(self, session_args: Dict = None, commit_on_exit: bool = False):
6767
self.session_args = session_args or {}
6868
self.commit_on_exit = commit_on_exit
6969

70+
async def _init_session(self):
71+
self.token = _session.set(_Session(**self.session_args))
72+
7073
async def __aenter__(self):
7174
if not isinstance(_Session, sessionmaker):
7275
raise SessionNotInitialisedError
7376

74-
self.token = _session.set(_Session(**self.session_args))
77+
await self._init_session()
7578
return type(self)
7679

7780
async def __aexit__(self, exc_type, exc_value, traceback):

tests/test_session.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -100,6 +100,14 @@ def test_outside_of_route_without_context_fails(app, db, SQLAlchemyMiddleware):
100100
db.session
101101

102102

103+
@pytest.mark.asyncio
104+
async def test_init_session(app, db, SQLAlchemyMiddleware):
105+
app.add_middleware(SQLAlchemyMiddleware, db_url=db_url)
106+
107+
await db()._init_session()
108+
assert isinstance(db.session, AsyncSession)
109+
110+
103111
@pytest.mark.parametrize("commit_on_exit", [True, False])
104112
@pytest.mark.asyncio
105113
async def test_db_context_session_args(app, db, SQLAlchemyMiddleware, commit_on_exit):

0 commit comments

Comments
 (0)