我一直在通过隐藏和恢复一些代码来测试应用程序,而我 确定收到的密钥是好的(第一块),和 正在创建实体(第二块)。什么行不通 正在创建一个活动实例 - 引发BadKeyError(第三个块)
我添加了控制器代码,型号代码和回溯 日志页面中的错误。
# Controller Code
class ActivityHandler(FacebookEnabled):
def get(self):
# i.e. fbid / headline id / upvote. This works
actor_id = self.request.get('actor_id')
object_id = self.request.get('object_id')
# creating actor and object from keys (actor_id and object_id).
# This works.
actor = models.Person.get(actor_id)
object = models.Headline.get(object_id)
logging.info("Actor " + str(actor) +": " + str(actor.name) +
" object " + str(object) + ": " + str(object.title))
# THIS IS WHAT SEEMS TO RAISE AN EXCEPTION
activity = models.Activity(actor, object, action='upvote')
activity.put()
# Model Code
class Activity(polymodel.PolyModel):
# User causing the action i.e. a person
actor = db.ReferenceProperty(Person, required=True,
collection_name='actors')
# The object being the subject of the action i.e. headline
object = db.ReferenceProperty(Headline, required=True,
collection_name='objects')
# The action being made
action = db.StringProperty(required=True, choices=['upvote','downvote'],
default='upvote')
追溯
Name must be string type, not Headline
Traceback (most recent call last):
File "/base/python_runtime/python_lib/versions/1/google/appengine/
ext/webapp/__init__.py", line 511, in __call__
handler.get(*groups)
File "/base/data/home/apps/libnentest/2.343063076026692316/main.py",
line 125, in get
activity = models.Activity(actor, object, action='upvote')
File "/base/python_runtime/python_lib/versions/1/google/appengine/
ext/db/__init__.py", line 726, in __init__
key_name.__class__.__name__)
BadKeyError: Name must be string type, not Headline
答案 0 :(得分:2)
object
始终是一个糟糕的名称选择,很可能导致异常。
答案 1 :(得分:1)
PolyModel的构造函数是这样的:class PolyModel(parent=None, key_name=None, **kwds):
所以你传递标题对象作为key_name,看起来它必须是来自堆栈跟踪的字符串。
从阅读docs我认为你想要做的是:
activity_kwargs = {
'actor' : actor,
'object' : object',
'action' : 'upvote',
}
activity = models.Activity(**activity_kwargs)
activity.put()
旁注:请勿将object
用作变量名称,因为它是内置关键字。