0

我正在尝试使用 python 中的以下代码在谷歌应用商店中调用实体的特定模型:

class Profile(BlogHandler):
    def get(self):
        user = users.get_current_user()

        if user:
            user = users.get_current_user()
            user_db_qry = User.query(User.theid == user.federated_identity())
            #theid is how I have saved each user's federated id in the User entity in the datastore
            user_db_list = user_db_qry.fetch(1)
            profile_user = user_db_list[0]
            profile_id = profile_user.key().id_or_name()
            #I am trying to get the datastore created ID/Name here and this is the line that gives me the error

            self.redirect('/profile/%s' % str(profile_id))
        else:
            self.redirect("/about")

所以我不太确定出了什么问题。我的查询不正确吗?

4

3 回答 3

4

首先,我对 GAE 没有任何经验。这个答案完全基于 API 文档

文档声称只有模型实例具有key()返回Key的方法。不过,这个User似乎是它自己的实体。

您可以使用直接方法,而不是尝试访问密钥实例:

profile_id = profile_user.user_id()
profile_nick = profile_user.nickname()

如果要调查key用户成员包含的内容,可以通过检查它来进行调试:

print type(profile_user.key)
print dir(profile_user.key)

更新

在您的评论中,您澄清说您正在使用解释问题的NDB变体。NDB Key Class与DB Key Class不同。它没有id_or_name()方法。它有什么:

id()返回最后一个 (kind, id) 对中的字符串或整数 id,如果键不完整,则返回 None。

string_id()返回最后一个 (kind, id) 对中的字符串 id,如果键具有整数 id 或不完整,则返回 None。

integer_id()返回最后一个 (kind, id) 对中的整数 id,如果键具有字符串 id 或不完整,则返回 None。

于 2012-06-30T04:15:21.463 回答
2
        profile_id = profile_user.key().id_or_name()

不需要第一组括号。

        profile_id = profile_user.key.id_or_name()
于 2012-06-30T03:37:42.090 回答
0

根据您在其他地方写的内容,您是如何为实体分配密钥的?你是给他们取名字吗?

如果您使用的关键路径以这样的结尾:(注意:我不是指父级,只是关键路径)

ndb.Key.from_path(..."User", "harold")

对于您的键,则键将为其 id 返回 None 但应该(如果ndb与 类似db)具有 name 属性。

解决这个问题的最简单方法是在 SDK 中运行您的应用程序,然后转到http://localhost:8080/_ah/admin,打开交互式控制台并尝试(可能是所有)属性,直到获得所需的属性。使用应用程序引擎,它通常有助于捕获奇怪的错误(例如,如果您尝试将它们与 kewyord 参数而不是位置参数一起使用,许多 API 调用会特别失败,等等)

我还建议尝试从您生成的密钥ndb.Key.from_path()到用户实例进行查找,看看您是否正确实例化/获取/无论您的密钥。

于 2012-06-30T05:26:20.827 回答