我们的项目中有这个代码,用于在数据库中读取/写入行
@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
块,只在Python对象中设置属性,如果在数据库中设置它已成功。