此交易方法是否有效? [英] Will this transaction method work?

查看:108
本文介绍了此交易方法是否有效?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图为应用引擎数据存储区编写一个事务性方法,但很难测试它是否正常工作,所以我试图首先验证我的方法。我有一个post请求,检查一个属性是否为true,如果不是true,则执行其他操作并将其设置为true。

I'm trying to write a transactional method for the app engine datastore but it's hard to test if it's working so I'm trying to validate my approach first. I have a post request that checks if a property is true, and if not true then do something else and set it to true.

def post(self):
    key = self.request.get('key')
    obj = db.get(key)
    if obj.property is False:
        update_obj(ojb.key()) // transactional method to update obj and set value to True

    if obj.property is True:
        // do something else


推荐答案


def post(self):
    key = self.request.get('key')
    # this gets the most recent entity using the key
    obj = db.get(key)
    if not obj.property:
        # You should do the most recent check inside the transaction. 
        # After the above if-check the property might have changed by 
        # a faster request.
        update_obj(ojb.key()) # transactional method to update obj and set value to True

    if obj.property:
       # do something else

将交易视为一组实体上的所有执行或全部失败的操作。

Consider transactions as a group of actions on an entity that will all execute or all fail.

交易确保其内的任何内容都将保持一致。如果某件事情改变了一个实体,并且变得与以前不同,交易将会失败,然后再次重复。

Transactions ensure that anything inside them will remain consistent. If something alters an entity and becomes different than it was, the transaction will fail and then repeat again.

如果我理解您需要的是另一种方法:

Another approach if I understand what you need:

def post(self):
    key = self.request.get('key')
    self.check_obj_property(key)
    # continue your logic

@db.transctional
def check_obj_property(key):
    obj = db.get(key)
    if obj.property:
        #it's set already continue with other logic
        return
    # Its not set so set it and increase once the counter. 
    obj.property = True
    # Do something else also?
    obj.count += 1
    # Save of course
    obj.put()

正如您所看到的,我已将所有支票放入交易中。
上面的代码,如果同时运行,只会增加一次一次
假设它像一个计数器,它计数 obj.property 已被设置为 True

As you see I've put all my checks inside a transaction. The above code, if run concurrently, will only increase the count once. Imagine it like a counter that counts how many times the obj.property has been set to True

这篇关于此交易方法是否有效?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆