ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

python – 从模型中获取JSONAPI模式

2019-07-01 15:43:32  阅读:293  来源: 互联网

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


在我的Rest应用程序中,我希望像JSONAPI格式一样返回json,但是我需要为它创建Schema类并再次创建我模型中已经存在的每个字段.因此,我不能在模型类中创建每个字段,而不是从DB模型中获取它.
下面是我的模特课

class Author(db.Model):
  id = db.Column(db.Integer)
  name = db.Column(db.String(255))

我在下面定义Schema.

class AuthorSchema(Schema):
    id = fields.Str(dump_only=True)
    name = fields.Str()
    metadata = fields.Meta()

    class Meta:
        type_ = 'people'
        strict = True

所以在这里,id和name我已经定义了两次.所以在marshmallow-jsonapi中有任何选项可以在模式类中指定模型名称,因此它可以从模型中获取所有字段
注意:我正在使用marshmallow-jsonapifor它,我已经尝试过marshmallow-sqlalchemy,它有这个选项,但它不会以JSONAPI格式返回json

解决方法:

您可以将flask-marshmallow的ModelSchema和marshmallow-sqlalchemy与marshmallow-jsonapi结合起来使用警告,您必须继承子类不仅包括Schema类,还包括SchemaOpts类,如下所示:

# ...
from flask_marshmallow import Marshmallow
from marshmallow_jsonapi import Schema, SchemaOpts
from marshmallow_sqlalchemy import ModelSchemaOpts


# ...

ma = Marshmallow(app)

# ...

class JSONAPIModelSchemaOpts(ModelSchemaOpts, SchemaOpts):
    pass


class AuthorSchema(ma.ModelSchema, Schema):
    OPTIONS_CLASS = JSONAPIModelSchemaOpts

    class Meta:
        type_ = 'people'
        strict = True
        model = Author

# ...
foo = AuthorSchema()
bar = foo.dump(query_results).data # This will be in JSONAPI format including every field in the model

标签:python,flask,flask-sqlalchemy,marshmallow,flask-restplus
来源: https://codeday.me/bug/20190701/1348487.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有