如何使用python和ndb模型循环以下数据存储数据并返回到json.dumps?

2024-04-19 07:12:10 发布

您现在位置:Python中文网/ 问答频道 /正文

[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从googleappengine数据存储中查询上述数据,但无法将其循环到JSON中。我也不太明白钥匙的概念,即使我看过文件。在

除了希望了解如何无限制地将带有密钥的整个对象转储到JSON中之外,您知道我如何提取“key”(字符串)、“email”和“created”(日期时间)吗?顺便说一下,我正在检索所有的数据。在

例如:

^{pr2}$

Tags: 数据keycomauthjsonidsdatetimeemail
1条回答
网友
1楼 · 发布于 2024-04-19 07:12:10

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

相关问题 更多 >