In Google App Engine, how can I work with eventual consistency in handling form submissions?

前端 未结 2 676
既然无缘
既然无缘 2021-01-14 02:44

I\'ve noticed that, with eventual consistency, the common form-processing workflow that I am used to (submit -> create/update record -> redirect -> reload) doesn\'t work. Up

2条回答
  •  不要未来只要你来
    2021-01-14 03:32

    Try to restructure your code so that you are getting by key (which always gives you the most recent data) instead of doing a query. I realize this isn't always possible, but I'll give you a recent example of something that worked for me.

    I have a user dashboard where a user can create and delete "items". My entities looked like this:

    class User(ndb.Model)
        ...
    
    class Item(ndb.Model)
        user = ndb.KeyProperty(User, required=True)
    

    In the past, I would do a query like this when responding to a GET request for the user dashboard.

    items = Item.query(user=user.key)
    

    This was a bad experience because a user would delete an item and after the POST/redirect/GET the just deleted item would again appear in the dashboard because of eventual consistency.

    To fix this, I changed my User entity to have a list of Items like this:

    class User(ndb.Model)
        items = ndb.KeyProperty(repeated=True)
        ...
    

    Now, when I show the dashboard, I do this:

    items = ndb.get_multi(user.items)
    

    Since I am now getting by key, the data is always up to date.

    This works for me because a user won't have that many items. If a user could have thousands of items, however, this approach wouldn't work because of the entity size limit.

提交回复
热议问题