繁体   English   中英

从服务器(python)向客户端发送数据库 model 的整洁 json 数据

[英]send tidy json data of a database model from server(python) to client

我正在使用 appengine,webapp2 框架。 我有以下 model:

class Match(db.Model):
    date_time = db.DateTimeProperty()
    team1 = db.StringProperty()
    team2 = db.StringProperty()
    venue = db.StringProperty()
    result = db.IntegerProperty()

现在在客户端,一个事件向我的一个views发出发布请求,基于该发布请求,我想发送 json 数据,jQuery/javascript 可以轻松读取这些数据。

最好的方法是什么?

在模型中:

class DictModel(db.Model):
    def to_dict(self):
       return dict([(p, unicode(getattr(self, p))) for p in self.properties()])


class Match(DictModel):
    date_time = db.DateTimeProperty()
    team1 = db.StringProperty()
    team2 = db.StringProperty()
    venue = db.StringProperty()
    result = db.IntegerProperty()

并在意见中:

import json
self.response.out.write(json.dumps([m.to_dict() for m in matches]))

首先,我会推荐使用 guido 的 ndb 而不是旧的 db 模块。 但实际上旧的 db 模块和 ndb 都有适合你的解决方案。 首先,您需要将 model 从 object 转换为 json 可序列化结构。 特别是一本 python 字典。

旧数据库

dict = db.to_dict(匹配度)

国家发展银行

dict = Matchentity.to_dict()

现在你必须将它序列化为 json,这并不像你想象的那么简单,因为有一些你必须处理的属性,因为它们的值在 json 中没有多大意义。在新的 ndb 中你可以简单地通过使用排除这些在 to_dict() 方法和旧数据库中排除参数,为每个 model 编写一个特定的方法可能是一个更好的主意。然后使用 json.dump(dict) 在 ndb 邮件列表上对此有一些很好的讨论。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM