我增加了一些意見
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
考慮交易爲一組,將全部執行,要麼全部失敗上的實體動作可以發佈您的代碼。
確保其內的任何內容都將保持一致。如果某件事情改變了一個實體並且變得與以前不同,那麼交易將會失敗,然後再次重複。
另一種方法,如果我知道你需要什麼:
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
多少次。不要用'is'做布爾測試。只需使用'if not obj.property:'和'else:'。 – jonrsharpe