【发布时间】:2017-06-07 11:56:04
【问题描述】:
我有一个函数fn() 需要以原子方式执行一些数据库工作,这些工作依赖于某些数据集在其执行期间不会发生变化(大多数情况下都是如此)。
在 Django 中实现这一点的正确方法是什么?基本上我想做这样的事情:
def ensure_fn_runs_successfully():
# While commit unsuccessful, keep trying
while not fn():
pass
@transaction.atomic
def fn():
data = read_data_that_must_not_change()
... do some operations with the data and perform database operations ...
# Assume it returns true if commit was successful, otherwise false
return commit_only_if_the_data_actually_didnt_change()
@transaction.atomic 解决了部分问题(数据库应该只看到fn 运行之前或fn 成功运行之后的状态),但我不确定是否存在一个好的原语来做commit_only_if_the_data_actually_didnt_change,如果失败则重试操作。
要验证数据没有改变,只需检查查询返回的项目数是否与函数开始时相同即可;但是,我不知道是否有任何原语可以让您同时做出检查和提交决定/没有竞争条件。
【问题讨论】:
-
提供一个最小、完整和可验证的示例将真正帮助我们为您的问题提供完整的答案。
标签: python django locking atomic