为数据库连接提供before_request和teardown_request [英] Flask before_request and teardown_request for DB connections

查看:275
本文介绍了为数据库连接提供before_request和teardown_request的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据Flaskr的教程,数据库连接应该在每个会话之前打开和关闭:

  @ 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自动处理连接管理?

解决方案SQLAlchemy不知道你的Flask应用程序。因此,如果你想使用纯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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆