python - 使用ndb和python从GAE中通过URL传递的自动分配的ID中检索 key

标签 python google-app-engine key google-cloud-datastore

我已经为此苦苦挣扎了几个小时并尝试了一切!

所以基本上

我有一个名为 City 的类(class):

class City(ndb.Model):
    _parent = None
    city = ndb.StringProperty(required=True)
    created = ndb.DateTimeProperty(auto_now_add=True)

当我创建一个新城市时,它会被赋予一个自动ID,例如6438740092256256

后来我想在小时候向这个城市添加一个餐厅实体。所以我在 url 中传递了城市 ID,如下所示:

http://www.edkjfsk.com/addrestaurant/6438740092256256

这导致了这段代码

class PostRestaurant(webapp2.RequestHandler):
    def post(self, resource):
        key = ????

其中资源为 6438740092256256

我想要做的是能够使用 6438740092256256 从 URL 检索 key 。然而,我尝试过的每一种方法都会导致未知错误。

我已经尝试了一切,包括 key = :

City.get_by_id(int(resource))

ndb.Key(City, resource).get()

ndb.Key('City', int(resource))

等等

最佳答案

您将在此处获取 urlsafe 字符串。

this_key = ndb.Key(urlsafe=resource)
query_result_as_entity = this_key.get()

将 urlsafe 字符串转换为 key 后,您可以对其执行 get() 操作。

关于python - 使用ndb和python从GAE中通过URL传递的自动分配的ID中检索 key ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27285058/

相关文章:

python - 使用重复的键属性序列化 NDB 模型

python - 将字典中的值从 str 转换为 float

python - Django 这么慢? errno 32 管道破裂? dcramer-django-哨兵-?静态文件夹?

Python - 计算列表中的元素

python - 使用 GAE 的 Yaml 寻址和模板不起作用? TemplateDoesNotExist 只是通过 yaml 中的简单更改?

database - 如何快速获取 leveldb 中的确切键数?

javascript - 如何创建递归对象树数组以供以后迭代?

python - 类型错误 : 'module' object is not callable Tensorboard in Keras

python - 使用 pandas to_csv 时删除标题中的前导逗号

google-app-engine - 将 Google App Engine 应用程序升级到灵活环境时,如何运行 Google 的 aefix 工具?