フラスコのドキュメントによると、アプリのコンテキストが切断されたときにデータベース接続を閉じる必要があります。
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
消えるように)。これにより、接続が自動的に閉じられると思いました(dbドライバーが接続を閉じるためdel
)。接続を明示的に閉じることの利点は何ですか?