背景
我们的项目中有这段代码,用于从数据库中的一行读取和写入
@property
def title_str(self) -> str:
return self._title_str
@title_str.setter
def title_str(self, i_new_title: str):
self._title_str = i_new_title
self._update(db.Schema.PhrasesTable.Cols.title, i_new_title)
setter 更新模型对象和数据库
问题与疑问
我们担心如果这些陈述之一
self._title_str = i_new_title
self._update(db.Schema.PhrasesTable.Cols.title, i_new_title)
失败而另一个成功,模型对象中的值与我们数据库中的值之间会不一致
我们如何避免这种风险?
推测
也许有一种方法可以使两个Python语句“原子”,这样如果一个语句失败,另一个语句就会恢复,或者这里的方法只是存储旧值并在捕获异常时将它们写回?
<小时/>感谢您的帮助!
最佳答案
@property
def title_str(self) -> str:
return self._title_str
@title_str.setter
def title_str(self, i_new_title: str):
try:
self._update(db.Schema.PhrasesTable.Cols.title, i_new_title)
except TheExceptionRaisedByYourDb:
pass
else: # there was no exception
self._title_str = i_new_title
使用 try ... except ... else
block ,并且仅在数据库中设置属性成功时才在 Python 对象中设置该属性。
关于python - 确保如果两个语句之一失败,则两个语句的最终结果不会发生变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47953294/