是否应在每次请求后关闭数据库连接?

时间:2017-12-10 20:32:11

标签: python flask

我正在使用python flask创建一个基本的API并且遇到了这个文档(类似的建议在其他文档中也很好):

http://flask.pocoo.org/docs/0.12/tutorial/dbcon/

本文档建议像这样的数据库连接:

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()

最初,我应该触发应用程序关闭app.teardown_appcontext。但是当我测试时,我发现它在每个请求结束时被触发。我有两个问题:

1)为什么每次请求都会触发teardown_appcontext。然后它与teardown_request有何不同?

2)为每个请求获取数据库连接并在之后关闭是不是一个坏主意?我认为只有一次完整的应用程序运行才能获得连接。如果这是一个坏主意,应该如何获取和关闭数据库连接?

1 个答案:

答案 0 :(得分:1)

在处理数据库时池连接是一种很好的做法。您正在使用的库正在进行中并且是单个进程 - 这与大多数数据库客户端不同,后者是基于网络的和多用户的。当一切都是本地的时,创建连接的开销要低得多。