gpt4 book ai didi

python - 每次请求后都应该关闭数据库连接吗?

转载 作者:行者123 更新时间:2023-11-28 18:17:01 24 4
gpt4 key购买 nike

我正在使用 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) 为每个请求获取数据库连接然后关闭不是个坏主意吗?我认为对于完整的应用程序运行,应该只获取一次连接。如果这是一个坏主意,应该如何获取和关闭数据库连接?

最佳答案

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

关于python - 每次请求后都应该关闭数据库连接吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47743154/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com