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
是现在的模型保存。否则,不清楚 future
在 put
上下文中的用途。
什么时候 self
和 future
在 put
的上下文中不同?这里的 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 聚合模型。我不相信 self
和 future.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/