Will this transaction method work?

2019-08-14 16:32发布

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条回答
兄弟一词,经得起流年.
2楼-- · 2019-08-14 16:58

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

查看更多
登录 后发表回答