@@ -21,9 +21,6 @@ def create_middleware_and_session_proxy():
21
21
_Session : Optional [async_sessionmaker ] = None
22
22
_session : ContextVar [Optional [AsyncSession ]] = ContextVar ("_session" , default = None )
23
23
_multi_sessions_ctx : ContextVar [bool ] = ContextVar ("_multi_sessions_context" , default = False )
24
- _task_session_ctx : ContextVar [Optional [AsyncSession ]] = ContextVar (
25
- "_task_session_ctx" , default = None
26
- )
27
24
_commit_on_exit_ctx : ContextVar [bool ] = ContextVar ("_commit_on_exit_ctx" , default = False )
28
25
# Usage of context vars inside closures is not recommended, since they are not properly
29
26
# garbage collected, but in our use case context var is created on program startup and
@@ -92,25 +89,22 @@ async def execute_query(query):
92
89
```
93
90
"""
94
91
commit_on_exit = _commit_on_exit_ctx .get ()
95
- session = _task_session_ctx .get ()
96
- if session is None :
97
- session = _Session ()
98
- _task_session_ctx .set (session )
99
-
100
- async def cleanup ():
101
- try :
102
- if commit_on_exit :
103
- await session .commit ()
104
- except Exception :
105
- await session .rollback ()
106
- raise
107
- finally :
108
- await session .close ()
109
- _task_session_ctx .set (None )
110
-
111
- task = asyncio .current_task ()
112
- if task is not None :
113
- task .add_done_callback (lambda t : asyncio .create_task (cleanup ()))
92
+ # Always create a new session for each access when multi_sessions=True
93
+ session = _Session ()
94
+
95
+ async def cleanup ():
96
+ try :
97
+ if commit_on_exit :
98
+ await session .commit ()
99
+ except Exception :
100
+ await session .rollback ()
101
+ raise
102
+ finally :
103
+ await session .close ()
104
+
105
+ task = asyncio .current_task ()
106
+ if task is not None :
107
+ task .add_done_callback (lambda t : asyncio .create_task (cleanup ()))
114
108
return session
115
109
else :
116
110
session = _session .get ()
@@ -126,7 +120,6 @@ def __init__(
126
120
multi_sessions : bool = False ,
127
121
):
128
122
self .token = None
129
- self .multi_sessions_token = None
130
123
self .commit_on_exit_token = None
131
124
self .session_args = session_args or {}
132
125
self .commit_on_exit = commit_on_exit
0 commit comments