AppEngine使ndb模型json可序列化 [英] AppEngine Making ndb models json serializable

查看:157
本文介绍了AppEngine使ndb模型json可序列化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们有一个我们想让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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆