为数据库连接提供before_request和teardown_request [英] Flask before_request and teardown_request for DB connections
问题描述
@ app.before_request
def before_request():
g.db = connect_db()
@ app.teardown_request
def teardown_request(例外):
db = getattr(g, 'db',None)
如果db不是None:
db.close()
但是,使用sqlite3时就是这种情况。
我的问题是:当使用postressql和SqlAlchemy时,连接是否需要以同样的方式打开和关闭,还是SQLAlchemy自动处理连接管理?
在没有足够的db连接知识的情况下,自己处理这些主题,可能会导致持久连接和连接池到非常差的表现和错误。
最佳实践是使用 Flask-SQLAlchemy 来抽象数据库连接管理。
According to the Flaskr tutorial, db connection should be opened and closed before each session:
@app.before_request
def before_request():
g.db = connect_db()
@app.teardown_request
def teardown_request(exception):
db = getattr(g, 'db', None)
if db is not None:
db.close()
However, this is the case when using sqlite3.
my question is: when using postressql and SqlAlchemy - do connections need to be opened and closed in the same way, or does SQLAlchemy takes care of connection management automatically?
SQLAlchemy doesn't know about your Flask application. So, if you want to use pure SQLAlchemy you need to manage connections.
Dealing with these topics by yourself without enough knowledge on db connections, persistent connections and connection pooling may lead to very poor performance and errors. Best practice is to use Flask-SQLAlchemy to abstract db connection management.
这篇关于为数据库连接提供before_request和teardown_request的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!