在SQLAlchemy的init_app函数中配置SQLALCHEMY_COMMIT_ON_TEARDOWN为True是可以在请求结束时自动提交数据库数据,不用手动提交,但是
@app.teardown_appcontext
def shutdown_session(response_or_exc):
if app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN']:
if response_or_exc is None:
self.session.commit()
self.session.remove()
return response_or_exc
出现提交失败的话没有进行处理,会报错,所以这里需要修改一下
@app.teardown_appcontext
def shutdown_session(response_or_exc):
if app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN']:
if response_or_exc is None:
# 提交失败后,回滚,防止报错
try:
self.session.commit()
except BaseException as e:
self.session.rollback()
self.session.remove()
return response_or_exc