生成marshmallow-sqlalchemy ModelSchema,如JSONAPI格式

时间:2017-11-07 08:33:44

标签: python json flask flask-sqlalchemy flask-restplus

我正在使用flask-Restplus for API,而在GET方法中我想返回JSON,如JSONAPI格式:

{"data":[
  {
     "type":"articles",
     "id":"1",
     "attributes":{
        "title":"JSON API paints my bikeshed!"
     },
     "relationships":{
        "author":{
           "links":{
              "self":"http://example.com/articles/1/relationships/author",
              "related":"http://example.com/articles/1/author"
           },
           "data":{
              "type":"people",
              "id":"9"
           }
        },
        "comments":{
           "links":{
              "self":"http://example.com/articles/1/relationships/comments",
              "related":"http://example.com/articles/1/comments"
           },
           "data":[
              {
                 "type":"comments",
                 "id":"5"
              },
              {
                 "type":"comments",
                 "id":"12"
              }
           ]
        }
     },
     "links":{
        "self":"http://example.com/articles/1"
     }
  }]}

我正在做的是创建Schema类并提及其中的每个字段,而不是根据我的数据库模型进行手动工作。

所以我使用了marshmallow-sqlalchemy并在其中提到了模型名称,但它返回了简单的JSON。我想通过使用marshmallow-sqlalchemy来获得与JSONAPI相同的JSON结构。

我该怎么做?

0 个答案:

没有答案