max
max

Reputation: 52323

Why teardown_appcontext required to close db connection?

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?

Upvotes: 4

Views: 3377

Answers (1)

Tzvika Mordoch
Tzvika Mordoch

Reputation: 193

When the reference to the connection is lost it still doesn't close the connection.

A lot of databases also maintain open connections, if you don't "inform" it that the connection is closed the connection would still exist on the database side and continue to use resources etc..

This is not specific to python or flask.

Upvotes: 1

Related Questions