Skip to content

Commit 8e210de

Browse files
committed
fixing teardown_appcontext
1 parent 5a575e7 commit 8e210de

File tree

1 file changed

+15
-12
lines changed

1 file changed

+15
-12
lines changed

src/cs50/sql.py

Lines changed: 15 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -276,21 +276,16 @@ def execute(self, sql, *args, **kwargs):
276276
assert flask.current_app
277277

278278
# If new context
279-
if not hasattr(flask.g, "_connection"):
279+
# https://flask.palletsprojects.com/en/1.1.x/appcontext/#storing-data
280+
if "_connection" not in flask.g:
280281

281-
# Ready to connect
282-
flask.g._connection = None
283-
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()
289-
290-
# If no connection for context yet
291-
if not flask.g._connection:
282+
# Connect to database
292283
flask.g._connection = self._engine.connect()
293284

285+
# Disconnect from database later
286+
if _teardown_appcontext not in flask.current_app.teardown_appcontext_funcs:
287+
flask.current_app.teardown_appcontext(_teardown_appcontext)
288+
294289
# Use context's connection
295290
connection = flask.g._connection
296291

@@ -533,3 +528,11 @@ def _parse_placeholder(token):
533528

534529
# Invalid
535530
raise RuntimeError("{}: invalid placeholder".format(token.value))
531+
532+
533+
def _teardown_appcontext(exception=None):
534+
"""Closes context's database connection, if any."""
535+
import flask
536+
connection = flask.g.pop("_connection", None)
537+
if connection:
538+
connection.close()

0 commit comments

Comments
 (0)