AppEngine Making ndb模型json serializab

2024-09-30 20:23:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我们有一个ndb模型,希望使json可序列化。模型相当简单,大致如下:

class Pasta(ndb.Model):
   name = ndb.StringProperty()
   type = ndb.StringProperty()
   comments = ndb.JsonProperty()

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

json.dumps(Pasta.query(Pasta.name=="Ravioli").fetch())并将其返回给客户机,但它不断抛出json解析错误,因为类Pasta不是json可序列化的。所以,问题是,我们必须实现__str____repr__还是有一种更好的方法来实现它?


Tags: name模型json处理程序model序列化typecomments
3条回答

或者您可以向模型添加计算属性,如下所示:

class Taxes(ndb.Model):
    name = ndb.StringProperty()
    id = ndb.ComputedProperty(lambda self: self.key.id())

然后在get方法中,只要调用dict,就可以得到id

rows = [row.to_dict() for row in Taxes.query()]
self.response.write(json.dumps(rows))

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()])

我不相信有文档记录,但是对于现有的ext.db模型,可以使用db.to_dict()(请参见here)。

尽管使用db.ReferencePropertydb.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...

然后用这个编码:

JSONEncoder().encode(YourModel.all().fetch())

相关问题 更多 >