从Google App Engine Datastore检索JSON

3

我已经在GAE数据存储中存储了一些简单的数据。现在我想把它取出来,但是我希望以JSON格式呈现结果。有没有简单的方法可以做到这一点?

2个回答

5
你可以先将数据存储模型转换为字典,然后使用simplejson(Python 2.5)或json(Python 2.7)包将字典转换为JSON格式。通常情况下,你的处理程序最后一行会是这样的:
self.response.out.write(simplejson.dumps(some_datastore_entity.to_dict()))

新的ndb接口默认提供了一个to_dict方法,您可以在这里查看。


不仅 ndb 接口有一个 to_dict 方法:https://developers.google.com/appengine/docs/python/datastore/functions#to_dict - voscausa

1
class Handler(webapp2.RequestHandler):
    def get(self):
        <do your GQLQuery here>
        self.response.headers['Content-Type'] = 'application/json'
        self.response.body = json.dumps(<your data in dict or dict list>)
        self.response.set_status(200)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接