AppEngine使ndb模型json可序列化 [英] AppEngine Making ndb models json serializable
问题描述
我们有一个我们想让json序列化的ndb模型。这些模型非常简单:
类Pasta(ndb.Model):
name = ndb。 StringProperty()
type = ndb.StringProperty()
comments = ndb.JsonProperty()
然后在处理程序端,我们想要做一些事情:
$ b
json.dumps(Pasta.query(Pasta .name ==Ravioli)。fetch())
并将其返回给客户端,但由于类Pasta不是json序列化,所以它一直抛出json解析错误。所以,问题是,我们是否必须实现 __ str __
或 __ repr __
或者是否有一种更加方便的方法来实现它?
ndb.Model
to_dict()函数:
https://开发人员。 google.com/appengine/docs/python/ndb/modelclass#Model_to_dict
最简单的方法是:
json.dumps([p.to_dict()for p in Pasta.query(Pasta.name ==Ravioli)。fetch()])
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())
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
instances have a to_dict()
function:
https://developers.google.com/appengine/docs/python/ndb/modelclass#Model_to_dict
the simplest way is:
json.dumps([p.to_dict() for p in Pasta.query(Pasta.name == "Ravioli").fetch()])
这篇关于AppEngine使ndb模型json可序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!