【问题标题】:GAE NDB structured list into JsonGAE NDB结构化列表转换成Json
【发布时间】:2014-04-05 21:14:42
【问题描述】:

我最近从 ext.db 切换到新的 NDB 并遇到了困难。

我想将结构化列表转换为 Json 包,以便发送到 iPhone 应用程序。我收到“不是 JSON 可序列化”错误。我想打包,以便所有用户最喜欢的水果都转换为Json。如果用户喜欢苹果、橙子和草莓,那么在 Json 的 favorites 字段中(代码如下)应该包含所有三种水果以及相关的分数和 cmets。

我知道to_dict存在,还有jsonProperty,但是不知道怎么申请。

以下是我所拥有的:

class FavFruits(ndb.Model):
    fruit    = ndb.StringProperty()
    score    = ndb.IntegerProperty()
    comment  = ndb.TextProperty()

 class UserProfile(ndb.Model):
    uid            = ndb.StringProperty(required=True)
    favFruits      = ndb.StructuredProperty(FavFruits, repeated=True)

 @classmethod
 def makeJsonPackage(cls, uid):
      fruitList = UserProfile.query(UserProfile.uid == uid).get()
            entry = {}
            entry["uid"]           = fruitList.uid
            entry["favorites"]     = fruitList.favFruits
            return (entry)

 # down stream of the code
 jsonData = UserProfile.makeJsonPackage(uid)
 self.response.write(json.dumps(jsonData))

这不起作用.. 问题出在entry["favorites"] = fruitList.favFruits,因为我在将结构化列表转换为 Json 数据时遇到问题。

目标:发送favFruits 条目的整个列表(多个水果)。我想保留结构化列表,因为我想在用户请求时查询数据,比如“苹果”,这样我就可以显示水果(苹果)和相关的分数和 cmets。

任何帮助将不胜感激。

【问题讨论】:

    标签: python json database google-app-engine app-engine-ndb


    【解决方案1】:

    基于 AppEngine Making ndb models json serializabledocument,下面的代码应该可以工作。

    返回一个包含模型属性值的字典。属性值 对于 StructuredProperty 和 LocalStructuredProperty 是递归的 转换成字典。

    @classmethod
    def makeJsonPackage(cls, uid):
        fruitList = UserProfile.query(UserProfile.uid == uid).get()
        return json.dumps(fruitList.to_dict())
    

    更新1

    userPorfile = UserProfile.query(UserProfile.uid == uid).get()
    return json.dumps([k.to_dict() for k in userProfile.favFruits])
    

    额外:使用端点

    因为您想使用 AppEngine 作为您的移动应用程序的后端 api 服务器。首先检查 Endpoints API,它是专门为这种用途设计的。

    https://developers.google.com/appengine/docs/java/endpoints/

    基于端点,有一个名为 Endpoints Proto Datastore API 的谷歌支持包。它为 ndb 模型和端点提供了更直接的连接。刚开始有点难,但是知道怎么做之后,就很强大了,可以节省不少时间。

    http://endpoints-proto-datastore.appspot.com/

    更新 2:

    编辑1: 我为 ndb 模型写了一个 RESTFul api 生成器。

    # generate restful api in one line
    BigDataLab = EndpointRestBuilder(GPCode).build(
        api_name="BigDataLab",
        name="bigdatalab",
        version="v1",
        description="My Little Api"
    )
    

    回购:https://github.com/Tagtoo/endpoints-proto-datastore-rest

    【讨论】:

    • 感谢您的意见。我尝试了建议的更改,但我仍然遇到问题,因为我得到 AttributeError: 'list' object has no attribute 'to_dict' 我的实际数据库有其他列,如 loginDateTime 我不想要放入 JSON 包。是否有可能做到这一点?我需要转换为 dict 的只是 favFruits 条目,而不是 uid,还是我遗漏了什么?另外,感谢您对 Endpoints 的建议;我一定会在生产网站上对此进行调查。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-10
    • 1970-01-01
    • 2011-01-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多