在 Google App Engine 中,如何在处理表单提交时保持最终一致性? [英] In Google App Engine, how can I work with eventual consistency in handling form submissions?
问题描述
我注意到,在最终一致性的情况下,我习惯的通用表单处理工作流程(提交 -> 创建/更新记录 -> 重定向 -> 重新加载)不起作用.重定向后,新记录(可能)将无法显示.我应该如何处理表单以便在重新加载时显示更新?
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. Upon redirect, the new record (probably) won't be available for display. How should I handle forms so that updates are displayed upon reload?
我可以尝试使用强一致性,但作为 App Engine 文档 注释,更新仅限于 每秒更新一次.
I could try to use strong consistency, but as the App Engine documentation notes, updates are limited to one update per second.
那么,我如何处理提供即时用户反馈并最终保持一致性的表单?
So how can I process a form providing immediate user feedback with eventual consistency?
推荐答案
尝试重构您的代码,以便您按关键字获取(它始终为您提供最新数据)而不是执行查询.我意识到这并不总是可行的,但我会举一个最近对我有用的例子.
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)
过去,我会在响应用户仪表板的 GET 请求时执行这样的查询.
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)
这是一种糟糕的体验,因为用户会删除一个项目,并且在 POST/重定向/GET 之后,由于最终的一致性,刚刚删除的项目将再次出现在仪表板中.
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.
这篇关于在 Google App Engine 中,如何在处理表单提交时保持最终一致性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!