@@ -275,19 +275,24 @@ def execute(self, sql, *args, **kwargs):
275
275
# Infer whether app is defined
276
276
assert flask .current_app
277
277
278
- # If new context
278
+ # If no connections to any databases yet
279
+ if not hasattr (flask .g , "_connections" ):
280
+ setattr (flask .g , "_connections" , {})
281
+ connections = getattr (flask .g , "_connections" )
282
+
283
+ # If not yet connected to this database
279
284
# https://flask.palletsprojects.com/en/1.1.x/appcontext/#storing-data
280
- if "_connection" not in flask . g :
285
+ if id ( self ) not in connections :
281
286
282
287
# Connect to database
283
- flask . g . _connection = self ._engine .connect ()
288
+ connections [ id ( self )] = self ._engine .connect ()
284
289
285
290
# Disconnect from database later
286
291
if _teardown_appcontext not in flask .current_app .teardown_appcontext_funcs :
287
292
flask .current_app .teardown_appcontext (_teardown_appcontext )
288
293
289
- # Use context's connection
290
- connection = flask . g . _connection
294
+ # Use this connection
295
+ connection = connections [ id ( self )]
291
296
292
297
except (ModuleNotFoundError , AssertionError ):
293
298
@@ -533,6 +538,5 @@ def _parse_placeholder(token):
533
538
def _teardown_appcontext (exception = None ):
534
539
"""Closes context's database connection, if any."""
535
540
import flask
536
- connection = flask .g .pop ("_connection" , None )
537
- if connection :
541
+ for connection in flask .g .pop ("_connections" , {}).values ():
538
542
connection .close ()
0 commit comments