我有点难以理解我编写的与 Google App Engine 的 NDB 数据存储区的异步 API 一起使用的一些小任务的情况。概述是:我需要汇总用户的购买历史记录,并且“UserPurchase”对象引用购买的“产品”或“自定义”项目,以及购买它的“Establishment”,两者都使用 KeyProperty UserPurchase ndb.Model 中的属性。我想尽可能地并行化各种 NDB 查找,所以我非常接近 NDB 文档(位于https://cloud.google.com/appengine/docs/standard/python/ndb/async)并构建3 个小任务:
@ndb.tasklet
def get_establishment(purch):
resto = yield purch.p_establishment.get_async()
ret = {
"rkey": resto.key.urlsafe(),
"rname": resto.resto_name
}
raise ndb.Return(ret)
@ndb.tasklet
def get_item(purch):
item = yield purch.p_item.get_async()
if (purch.p_item.kind() == "Product"):
ret = {
"ikey": item.key.urlsafe(),
"iname": item.name
}
else:
ret = {
"ikey": item.key.urlsafe(),
"iname": item.cust_name
}
raise ndb.Return(ret)
@ndb.tasklet
def load_history(purch):
at, item = yield get_establishment(purch), get_item(purch)
ret = {
"date": purch.p_datetime,
"at_key": at.rkey,
"at": at.rname,
"item_key": item.ikey,
"item": item.iname,
"qty": purch.p_quantity,
"type": purch.p_type
}
raise ndb.Return(ret)
然后,我这样打电话:
pq = UserPurchase.query().order(-UserPurchase.p_datetime)
phistory = pq.map(load_history, limit = 20)
检索最近的 20 次购买以进行显示。但是,当我运行它时,我遇到了一个奇怪的异常,我不知道该怎么做……而且我对 tasklet 以及它们如何工作还不够熟悉,无法自信地说我知道发生了什么。如果有人能给我一些关于寻找什么的指示,我将非常感激......!这是我在运行上述代码时遇到的异常:
...
File "/Programming/VirtualCellar/server/virtsom.py", line 2348, in get
phistory = pq.map(load_history, limit = 20)
File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/ext/ndb/utils.py", line 160, in positional_wrapper
return wrapped(*args, **kwds)
File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/ext/ndb/query.py", line 1190, in map
**q_options).get_result()
File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/ext/ndb/tasklets.py", line 383, in get_result
self.check_success()
File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/ext/ndb/tasklets.py", line 624, in _finish
result = [r.get_result() for r in self._results]
File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/ext/ndb/tasklets.py", line 383, in get_result
self.check_success()
File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/ext/ndb/tasklets.py", line 430, in _help_tasklet_along
value = gen.send(val)
File "/Programming/VirtualCellar/server/virtsom.py", line 2274, in load_history
"at_key": at.rkey,
AttributeError: 'dict' object has no attribute 'rkey'
基于错误,似乎小任务不喜欢返回字典......