根据flask docs,当应用上下文崩溃时,我们应该关闭数据库连接:
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()
但是应用程序上下文的拆除不会删除(唯一)对数据库连接的引用(g.sqlite_db
消失时g
消失)吗?我认为这会自动关闭连接(因为数据库驱动程序会关闭连接del
)。显式关闭连接有什么好处?