确保如果两个语句中有一个失败,那么两个语句的最终结果都不会改变

2024-10-17 06:16:30 发布

您现在位置:Python中文网/ 问答频道 /正文

背景

我们的项目中有这样的代码,用于从数据库中的行进行读写

@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语句成为“原子”语句,这样,如果一个语句失败,另一个语句将被还原,或者这里的方法只是存储旧值并在捕获异常时将它们写回


谢谢你的帮助


Tags: 对象模型self数据库newdbtitleschema
1条回答
网友
1楼 · 发布于 2024-10-17 06:16:30
@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对象时才设置该属性

相关问题 更多 >