According to flask docs, we should close the database connection when app context tears down:
def get_db():
"""Opens a new database connection if there is none yet for the
current application context.
"""
if not hasattr(g, 'sqlite_db'):
g.sqlite_db = connect_db()
return g.sqlite_db
@app.teardown_appcontext
def close_db(error):
"""Closes the database again at the end of the request."""
if hasattr(g, 'sqlite_db'):
g.sqlite_db.close()
But wouldn't the tearing down of the app context remove the (only) reference to the database connection (as g.sqlite_db
disappears when g
disappears)? I thought that would automatically close the connection (since db driver would close the connection on del
). What's the benefit of the explicit closing of the connection?