[英]How can I better handle this Flask-SQLAlchemy commit/rollback?
I'm reviewing some old code I wrote and was looking at a shared commit function I had written to handle responses to the user on certain failures when attempting to commit changes to the database (such as deletes): 我正在查看我编写的一些旧代码,并查看了我编写的共享提交功能,该功能用于在尝试将更改提交给数据库(例如删除)时处理某些失败时对用户的响应:
def _commit_to_database():
"""A shared function to make a commit to the database and handle exceptions
if encountered.
"""
flask.current_app.logger.info('Committing changes to database...')
try:
db.session.commit()
except AssertionError as err:
flask.abort(409, err)
except (exc.IntegrityError, sqlite3.IntegrityError) as err:
flask.abort(409, err.orig)
except Exception as err:
flask.abort(500, err)
finally:
db.session.rollback()
I think I understand my thought process: attempt the commit
, upon certain failures trigger a flask.abort
to send the response back, but I believe I found that the database was left with an open session requiring a rollback when I did this and adding the rollback
into a finally
statement resolved this allowing me to still use the flask.abort
. 我认为我理解了我的思维过程:尝试执行commit
,在某些失败时触发flask.abort
将响应发送回去,但是我发现执行此操作并添加了rollback
到finally
语句解决了此问题,使我仍然可以使用flask.abort
。
The questions I have around me code are: 我对我的代码有以下疑问:
1) Is this a bug: will the Flask-SQLAlchemy extension not close out the session as normal; 1)这是否是一个错误:Flask-SQLAlchemy扩展是否不会正常关闭会话; is calling the rollback
on the finally
which will be triggering after the abort
going to affect successful commit
s? 在abort
将影响成功commit
的触发后将在finally
上调用rollback
吗?
2) If this is a bug: what should I be doing differently in handling the try-except-finally
and the db
session? 2)如果这是一个错误:在处理try-except-finally
和db
会话时,我应该做些什么?
You need to rollback when exception occurs and finally close the session: 您需要在发生异常时回滚并最终关闭会话:
def _commit_to_database():
"""A shared function to make a
commit to the database and
handle exceptions if encountered.
"""
flask.current_app.logger.info(
'Committing changes to db...'
)
try:
db.session.commit()
except AssertionError as err:
db.session.rollback()
flask.abort(409, err)
except (
exc.IntegrityError,
sqlite3.IntegrityError
) as err:
db.session.rollback()
flask.abort(409, err.orig)
except Exception as err:
db.session.rollback()
flask.abort(500, err)
finally:
db.session.close()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.