python - GAE NDB 结构化列表到 Json

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

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

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

我知道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 条目列表(多个水果)。我想保留 structuredList,因为我想在用户请求时查询数据,比如“苹果”,这样我就可以显示水果(苹果)以及相关的分数和评论。

任何帮助将不胜感激。

最佳答案

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

Returns a dict containing the model's property values. Property values for StructuredProperty and LocalStructuredProperty are recursively converted into dictionaries.

@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"
)

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

关于python - GAE NDB 结构化列表到 Json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22886900/

相关文章:

python - Django 设置模块和相对路径

json - 如何仅将 Spring Resttemplate 与 JSON 一起使用

mysql - 具有类似数组支持的数据库?

sql - Oracle 数据库在使用过程时无法识别类型

python - 在 Selenium Chromedriver、Python 中禁用 CSS 和图像

python - 如何分发ansible模块?

python - 在 Python 中存储多个数组

java - 使用 Jackson 将 json 扁平化为 map

java - 无法配置 Jackson 混音

php - 使用 PHP 从 MySQL 下载数据到 csv 文件