Cloud Datastore: ways to avoid race conditions

后端 未结 1 1775
悲哀的现实
悲哀的现实 2021-01-27 18:51

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

de         


        
相关标签:
1条回答
  • 2021-01-27 19:22

    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()
    
    0 讨论(0)
提交回复
热议问题