1

我使用mongoengine访问 mongoDB,我正在寻找一种简单的方法来实现乐观锁定方案。理想情况下,我想在文档中有一个version整数字段,并在每次修改文档时递增它,就像在mongodb 文档中描述的那样。如果文档对象的当前版本与 mongodb 中的文档版本不匹配,则保存文档应该会失败。

我对 mongoengine 有点迷茫。到目前为止,我实现了这一点。它有效,但我总是需要重新加载对象,这似乎真的不是最理想的。有更好的主意吗?

class OptimisticLockException(Exception):
    pass

class TodoList(Document):
    name = StringField()
    tasks = ListField(StringField())
    version = IntField()

    def add_task(self, task):
        qs = self.__class__.objects(id = self.id, version= self.version)
        nb_updated = qs.update_one(push__tasks = task, inc__version = 1)
        if nb_updated == 0:
            raise OptimisticLockException("Object was changed.")
        self.reload()  # <= CAN'T I AVOID THIS?

todo_list_1 = TodoList.objects.create(name = "Get rich",
                  tasks = ["Buy bitcoins", "Buy some more"])
todo_list_2 = TodoList.objects.get(name = "Get rich") # get the same

todo_list_1.add_task("Sell everything")
try:
    todo_list_2.add_task("Watch it crash!")
except OptimisticLockException:
    print "It crashed..."

todo_list_1.reload()
print todo_list_1.tasks  # prints [u'Buy bitcoins',u'Buy some more',
                         # u'Sell everything']
4

0 回答 0