Cloud Datastore: ways to avoid race conditions

老子叫甜甜 提交于 2019-12-02 17:02:34

问题


I have lots of views manipulating entities of same kind:

def view1(request, key):
    user = ndb.Key(urlsafe=key).get()
    user.x = 1
    user.put()
    ...

def view2(request, key):
    user = ndb.Key(urlsafe=key).get()
    user.y = 2
    user.put()
    ...

Obviously, this is error-prone due to possible race conditions (last wins):

  1. view1 reads whole user entity data (x=None, y=None)
  2. view2 reads whole user entity data (x=None, y=None)
  3. view1 user.x = 1 (x=1, y=None)
  4. view2 user.y = 2 (x=None, y=2)
  5. view1 user.put() (x=1, y=None)
  6. view2 user.put() (x=None, y=2)

What are best ways to fix this and what behaviour is considered most decent? Transactions (one of the requests is gonna fail, is this ok)?


回答1:


Wrap your get and put into a transaction. This will ensure you cannot stomp over a different update.

You can read more about transactions with the NDB Client Library documentation.

In your code, you could for example just use the NDB transaction decorator:

@ndb.transactional(retries=1)
def view1(request, key):
    user = ndb.Key(urlsafe=key).get()
    user.x = 1
    user.put()
    ...

@ndb.transactional(retries=1)    
def view2(request, key):
    user = ndb.Key(urlsafe=key).get()
    user.y = 2
    user.put()


来源:https://stackoverflow.com/questions/38955748/cloud-datastore-ways-to-avoid-race-conditions

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