@@ -275,19 +275,24 @@ def execute(self, sql, *args, **kwargs):
275275 # Infer whether app is defined
276276 assert flask .current_app
277277
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
279284 # 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 :
281286
282287 # Connect to database
283- flask . g . _connection = self ._engine .connect ()
288+ connections [ id ( self )] = self ._engine .connect ()
284289
285290 # Disconnect from database later
286291 if _teardown_appcontext not in flask .current_app .teardown_appcontext_funcs :
287292 flask .current_app .teardown_appcontext (_teardown_appcontext )
288293
289- # Use context's connection
290- connection = flask . g . _connection
294+ # Use this connection
295+ connection = connections [ id ( self )]
291296
292297 except (ModuleNotFoundError , AssertionError ):
293298
@@ -533,6 +538,5 @@ def _parse_placeholder(token):
533538def _teardown_appcontext (exception = None ):
534539 """Closes context's database connection, if any."""
535540 import flask
536- connection = flask .g .pop ("_connection" , None )
537- if connection :
541+ for connection in flask .g .pop ("_connections" , {}).values ():
538542 connection .close ()
0 commit comments