Skip to content

Commit 727df50

Browse files
committed
only calling teardown_appcontext once
1 parent a11c9b9 commit 727df50

File tree

1 file changed

+10
-6
lines changed

1 file changed

+10
-6
lines changed

src/cs50/sql.py

Lines changed: 10 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -281,7 +281,7 @@ def execute(self, sql, *args, **kwargs):
281281
# Join tokens into statement
282282
statement = "".join([str(token) for token in tokens])
283283

284-
# Connect to database (for transactions' sake)
284+
# Connect to database
285285
try:
286286

287287
# Infer whether Flask is installed
@@ -290,19 +290,23 @@ def execute(self, sql, *args, **kwargs):
290290
# Infer whether app is defined
291291
assert flask.current_app
292292

293-
# If no connection for app's current request yet
293+
# If new context
294294
if not hasattr(flask.g, "_connection"):
295295

296-
# Connect now
297-
flask.g._connection = self._engine.connect()
296+
# Ready to connect
297+
flask.g._connection = None
298298

299299
# Disconnect later
300300
@flask.current_app.teardown_appcontext
301301
def shutdown_session(exception=None):
302-
if hasattr(flask.g, "_connection"):
302+
if flask.g._connection:
303303
flask.g._connection.close()
304304

305-
# Use this connection
305+
# If no connection for context yet
306+
if not flask.g._connection:
307+
flas.g._connection = self._engine.connect()
308+
309+
# Use context's connection
306310
connection = flask.g._connection
307311

308312
except (ModuleNotFoundError, AssertionError):

0 commit comments

Comments
 (0)