如何使用mongoengine实现乐观锁定?

时间:2013-04-10 21:47:43

标签: mongoengine optimistic-locking

我使用mongoengine来访问mongoDB,我正在寻找一种实现乐观锁定方案的简单方法。理想情况下,我希望在文档中有一个version整数字段,并在每次修改文档时递增它,就像在mongodb documentation中描述的那样。如果当前版本的文档对象与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']

0 个答案:

没有答案