[User(key=Key('User', 5275456790069248), auth_ids=[u'abc@gmail.com'], created=datetime.datetime(2017, 8, 29, 22, 50, 36, 297407), email='abc@gmail.com'),
User(key=Key('User', 5838406743490560), auth_ids=[u'def@gmail.com'], created=datetime.datetime(2017, 8, 29, 16, 23, 16, 406468), email='def@gmail.com'),
User(key=Key('User', 6401356696911872), auth_ids=[u'ghi@gmail.com'], created=datetime.datetime(2017, 8, 30, 12, 34, 51, 816926), email='ghi@gmail.com')]
我设法使用 Python 从 Google App Engine 数据存储区查询上述数据,但无法将其循环到 JSON 中。即使我已经阅读了文档,仍然不太理解 key 的概念。
除了希望了解如何将带有 key 的整个对象无限制地转储到 JSON 中之外,您知道如何提取“ key ”(字符串形式)、“电子邮件”和“创建”(日期时间)吗?顺便说一句,我正在尝试检索所有数据。
例如:
users_new_list = []
allusers = User.query().fetch()
for user in all_users:
#How to get key in string and pass into 'users_new_list'
users_new_list.append(keyString)
最佳答案
NDB 中的 Key
是一个 python 类实例(一个对象),它无法在 json 中正确序列化。但它带有 .urlsafe()
方法,可将其转换为可以 json 转储的字符串。来自 Retrieving Entities from Keys :
You can also use an entity's key to obtain an encoded string suitable for embedding in a URL:
url_string = sandy_key.urlsafe()
This produces a result like agVoZWxsb3IPCxIHQWNjb3VudBiZiwIM which can later be used to reconstruct the key and retrieve the original entity:
sandy_key = ndb.Key(urlsafe=url_string)
现在,要对整个实体进行 json 编码,您必须编写一个自定义方法,该方法首先将 Key
属性转换为字符串。请参阅How to make a class JSON serializable
关于python - 如何使用python和ndb模型循环以下数据存储数据并返回到json.dumps?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45970096/