Flask before_request and teardown_request for DB connections

邮差的信 提交于 2019-12-12 18:40:20

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/20457667/flask-before-request-and-teardown-request-for-db-connections

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!