AppEngine 使 ndb 模型 json 可序列化 [英] AppEngine Making ndb models json serializable
问题描述
我们有一个 ndb 模型,我们想让 json 序列化.这些模型相当简单:
We have an ndb model that we would like to make json serializable. The models are fairly simple along the lines of:
class Pasta(ndb.Model):
name = ndb.StringProperty()
type = ndb.StringProperty()
comments = ndb.JsonProperty()
然后在处理程序方面我们想做一些事情:
Then on the handler side we would like to do something along the lines of:
json.dumps(Pasta.query(Pasta.name=="Ravioli").fetch())
并将其返回给客户端,但它一直抛出 json 解析错误,因为类 Pasta不是 json 可序列化的.所以,问题是,我们是否必须实现 __str__
或 __repr__
或者有更漂亮的方法来做到这一点?
json.dumps(Pasta.query(Pasta.name=="Ravioli").fetch())
and return it to the client, but it keeps throwing json parse errors since the class Pasta is not json serializable. So, the question is, do we have to implement __str__
or __repr__
or is there a niftier way to do it?
推荐答案
ndb.Model
实例有一个 to_dict()
函数:https://developers.google.com/appengine/docs/python/ndb/modelclass#Model_to_dict
ndb.Model
instances have a to_dict()
function:
https://developers.google.com/appengine/docs/python/ndb/modelclass#Model_to_dict
最简单的方法是:
json.dumps([p.to_dict() for p in Pasta.query(Pasta.name == "Ravioli").fetch()])
这篇关于AppEngine 使 ndb 模型 json 可序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!