Will this transaction method work?

纵饮孤独 提交于 2019-12-11 08:19:54

问题


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

回答1:


I am posting your code with some added comments

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()

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



来源:https://stackoverflow.com/questions/21813897/will-this-transaction-method-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!