@@ -56,6 +56,7 @@ def __init__(self, url, **kwargs):
56
56
# Create engine, disabling SQLAlchemy's own autocommit mode, raising exception if back end's module not installed
57
57
self ._engine = sqlalchemy .create_engine (url , ** kwargs ).execution_options (autocommit = False )
58
58
59
+ # Get logger
59
60
self ._logger = logging .getLogger ("cs50" )
60
61
61
62
# Listener for connections
@@ -77,7 +78,6 @@ def connect(dbapi_connection, connection_record):
77
78
# Register listener
78
79
sqlalchemy .event .listen (self ._engine , "connect" , connect )
79
80
80
-
81
81
# Test database
82
82
disabled = self ._logger .disabled
83
83
self ._logger .disabled = True
@@ -275,24 +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
279
- if not hasattr (flask .g , "_connection" ):
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" )
280
282
281
- # Ready to connect
282
- flask .g ._connection = None
283
+ # If not yet connected to this database
284
+ # https://flask.palletsprojects.com/en/1.1.x/appcontext/#storing-data
285
+ if self not in connections :
283
286
284
- # Disconnect later
285
- @flask .current_app .teardown_appcontext
286
- def shutdown_session (exception = None ):
287
- if flask .g ._connection :
288
- flask .g ._connection .close ()
287
+ # Connect to database
288
+ connections [self ] = self ._engine .connect ()
289
289
290
- # If no connection for context yet
291
- if not flask .g . _connection :
292
- flask . g . _connection = self . _engine . connect ( )
290
+ # Disconnect from database later
291
+ if _teardown_appcontext not in flask .current_app . teardown_appcontext_funcs :
292
+ flask . current_app . teardown_appcontext ( _teardown_appcontext )
293
293
294
- # Use context's connection
295
- connection = flask . g . _connection
294
+ # Use this connection
295
+ connection = connections [ self ]
296
296
297
297
except (ModuleNotFoundError , AssertionError ):
298
298
@@ -533,3 +533,10 @@ def _parse_placeholder(token):
533
533
534
534
# Invalid
535
535
raise RuntimeError ("{}: invalid placeholder" .format (token .value ))
536
+
537
+
538
+ def _teardown_appcontext (exception = None ):
539
+ """Closes context's database connection, if any."""
540
+ import flask
541
+ for connection in flask .g .pop ("_connections" , {}).values ():
542
+ connection .close ()
0 commit comments