确保如果两个语句中的一个未通过最终结果,则两个语句都不会发生变化

问题描述 投票:1回答:1

Background

我们的项目中有这个代码,用于在数据库中读取/写入行

@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更新模型对象和数据库

Problem and Question

我们担心如果其中一个陈述

self._title_str = i_new_title
self._update(db.Schema.PhrasesTable.Cols.title, i_new_title)

如果另一个成功失败,则模型对象中的值与数据库中的值之间将存在不一致

我们怎样才能避免这种风险?

Speculation

也许有一种方法可以使两个Python语句“原子化”,这样如果一个失败,另一个会被还原,或者这里的方法只是存储旧值并在我们捕获异常时将它们写回来?


感谢帮助!

python python-3.x orm setter
1个回答
1
投票
@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对象中设置属性,如果在数据库中设置它已成功。

© www.soinside.com 2019 - 2024. All rights reserved.