google-app-engine - ndb 模型的 _post_put_hook 什么时候有不同于自己的 future ?

标签 google-app-engine app-engine-ndb

Google App Engine 的 ndb 提供了一个 _post_put_hook(self, future) ,记录如下:

Hook that runs after put()

为了更好地理解这个钩子(Hook),我想知道 self 何时会与 future 参数的结果不同。

Model Hooks文档提供:

If you use post-hooks with asynchronous APIs, the hooks are triggered by calling check_result(), get_result() or yielding (inside a tasklet) an async method's future. Post hooks do not check whether the RPC was successful; the hook runs regardless of failure.

All post- hooks have a Future argument at the end of the call signature. This Future object holds the result of the action. You can call get_result() on this Future to retrieve the result; you can be sure that get_result() won't block, since the Future is complete by the time the hook is called.

但是,当我像这样异步调用 put 时:

from google.appengine.ext import ndb

class MyModel(ndb.Model):
   xyz = ndb.StringProperty()

   def _post_put_hook(self, future):
      print "self.xyz: {}, future.xyz: {}".format(
             self.xyz, future.get_result().get().xyz))

m = MyModel()
f = m.put_async()
f.wait()

m.xyz = 'abc'
f = m.put_async()
f.wait()

输出:

self.xyz: None, future.xyz: None
self.xyz: abc, future.xyz: abc

在“put_async”的上下文中,我认为人们可能合理地期望 self 是修改前的模型,而 future 是现在的模型保存。否则,不清楚 futureput 上下文中的用途。

什么时候 selffutureput 的上下文中不同?这里的 future 的目的是什么?

最佳答案

我相信答案在描述中:

Post hooks do not check whether the RPC was successful; the hook runs regardless of failure.

future 可以包含执行 put() 时失败的原因。您可以使用此知识通过 Hook 处理放置失败的情况。例如,如果您的 _post_put_hook 负责根据模型的属性递增关联的 SUM 聚合模型,它可以先检查 put 是否成功,然后再尝试递增关联的 SUM 聚合模型。我不相信 selffuture.get_result().get() 的值会有所不同,只要 RPC 没有失败。

总是有可能在该请求的 put 之后但在执行 _post_put_hook 之前,另一个请求更新了模型,其中 future.get_result()。 get(use_cache=False) 可能会返回不同的值。

关于google-app-engine - ndb 模型的 _post_put_hook 什么时候有不同于自己的 future ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15733546/

相关文章:

java - 无法对 DATASTORE 中的数据进行排序

google-app-engine - ndb 在没有父级的情况下按 ID 检索实体键

database - 如何更新 Google App Engine NDB 对象上的数据,以便它可以同时进行多次写入

python - 从 Python 中删除 GAE NBD 实体并刷新 Memchach 后,数据存储查看器中仍然可以看到它们

google-app-engine - 使用 GAE 限制对静态文件的访问

python - 既然不允许使用 Content-Length header ,是否可以在 GAE 应用程序中设置 blob 下载大小?

python - 如何在 GAE Python 中查询结构化属性内的计算属性

python - 在 Google App Engine NDB 中按字符串选择列

java - 如果我知道 ID,如何通过其唯一 ID 获取数据存储实体?

javascript - 无法对用户 API 后面的 App Engine 使用 Javascript 提取