AppEngine使ndb模型json可序列化

rdo*_*dev 22 python google-app-engine

我们有一个ndb模型,我们想让json序列化.这些模型非常简单:

class Pasta(ndb.Model):
   name = ndb.StringProperty()
   type = ndb.StringProperty()
   comments = ndb.JsonProperty()
Run Code Online (Sandbox Code Playgroud)

然后在处理程序方面,我们希望按照以下方式执行以下操作:

json.dumps(Pasta.query(Pasta.name=="Ravioli").fetch())并将其返回给客户端,但它继续抛出json解析错误,因为类Pasta不是json可序列化的.所以,问题是,我们必须实现__str____repr__还是有niftier办法做到这一点?

asc*_*d00 56

ndb.Model实例具有以下to_dict()功能: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()])
Run Code Online (Sandbox Code Playgroud)

  • 值得注意的是,`to_dict`在模型中不包含`key`.所以你可能希望做一些类似`json.dumps([dict(p.to_dict(),**dict(id = p.key.id()))的p in ... (11认同)
  • 如果有日期时间,则会出错 (6认同)
  • 为避免datetime错误,请使用`json.dumps(...,default = str)` (2认同)

JJ *_*wax 10

我不相信它有记录,但对于现有的ext.db模型,你可以使用db.to_dict()(见这里).

与谨慎,虽然db.ReferenceProperty年代和db.DateTimeProperty的,当您打电话,他们会抛出错误json.dumps().快速解决方案是自定义JSONEncoder:

from datetime import datetime, date, time
from google.appengine.ext import db

import json

class JSONEncoder(json.JSONEncoder):

    def default(self, o):
        # If this is a key, you might want to grab the actual model.
        if isinstance(o, db.Key):
            o = db.get(o)

        if isinstance(o, db.Model):
            return db.to_dict(o)
        elif isinstance(o, (datetime, date, time)):
            return str(o)  # Or whatever other date format you're OK with...
Run Code Online (Sandbox Code Playgroud)

然后用这个编码:

JSONEncoder().encode(YourModel.all().fetch())
Run Code Online (Sandbox Code Playgroud)