python - 从模型中获取 JSONAPI 模式

标签 python flask flask-sqlalchemy marshmallow flask-restplus

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

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

所以这里,idname我定义了两次。那么 marshmallow-jsonapi 中是否有任何选项可以在模式类中分配模型名称,以便它可以从 model
中获取所有字段 注意:我正在为它使用 marshmallow-jsonapi,我已经尝试过 marshmallow-sqlalchemy ,它有那个选项但它不返回 jsonJSONAPI 格式

最佳答案

您可以将 flask-marshmallowModelSchemamarshmallow-sqlalchemymarshmallow-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 - 从模型中获取 JSONAPI 模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47180202/

相关文章:

python - 如何向 python 子进程添加选项

Python setup.py 运行 shell 脚本

python - 如何修复 "Error during WebSocket handshake: Unexpected response code: 400"错误

join - Flask-SQLAlchemy 中的跨数据库连接

python - flask "get_or_404"类似功能但具有另一个状态代码

python - Left Outer 通过数据框上的键、系列上的索引将数据框与 Series 对象连接起来

python - 理解上下文管理器类中返回 self 的目的

python - 如何使用 pytz 和 tzlocal 测试日期时间转换?

python - 与 Flask、Postgres 的 SQLALchemy 数据库 session

python - 在 Flask SQLAlchemy 关联表中保存重复条目