4

根据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)。显式关闭连接有什么好处?

4

1 回答 1

1

当对连接的引用丢失时,它仍然不会关闭连接。

许多数据库还保持打开的连接,如果您不“通知”它连接已关闭,则连接仍将存在于数据库端并继续使用资源等。

这不是特定于 python 或烧瓶的。

于 2018-03-24T11:23:20.417 回答