【问题标题】:Python Flask_restplus flash_restx dynamic marshalling responsePython Flask Restplus flask restx 动态编组响应
【发布时间】:2020-09-11 14:26:42
【问题描述】:

是否可以动态修改编组响应模型(即:更改字段列表、添加掩码……)?

前:

from flask_restplus import Resource, fields

model = api.model('Model', {
    'name': fields.String,
    'address': fields.String,
    'date_updated': fields.DateTime(dt_format='rfc822'),
})

@api.route('/todo')
class Todo(Resource):
    @api.marshal_with(model, envelope='resource')
    def get(self, **kwargs):
        return db_get_todo()  # Some function that queries the db

这里的编组是用装饰器静态声明的。如果我想在用户不是管理员时屏蔽示例 date_updated,或者根据用户偏好我不能。

我看到了这个例子:https://blog.fossasia.org/dynamically-marshaling-output-in-flask-restplus/ 这很有趣,但它使用了另一个静态模型,所以它不是真正的动态并且意味着代码重复(当然我可以使用继承,...)

我希望能够动态更改字段或从可能来自数据库的列表中添加掩码(例如,用户偏好或权限)。

我已尝试手动编组答案

wanted_field_list='name,address'
return  marshal(db_get_todo(),model , mask=wanted_field_list),  200

如果我删除装饰器 @marshall_with 它可以完美运行,但缺点是我不再拥有 Swagger 文档

{ 'name':'blabla',
'address':'xxx'}

如果我保留装饰器,它仍然可以通过不需要的字段仍然使用 Null 值呈现:

{ 'name':'blabla',
'address':'xxx',
'date_updated : null}

这不是预期的结果

我试图转移到 flask_restx,但我的招摇根本没有渲染,我还有一些其他问题。

非常欢迎任何帮助!

【问题讨论】:

    标签: python marshalling flask-restplus flask-restx


    【解决方案1】:

    我知道它有点晚了,但无论如何都在这里,以防有人需要它:

    你有几个选择来完成你需要的事情:

    • 使用skip_none flag to true。这将忽略 date_updated 字段为 null 时的响应。
    • 调用 API 时使用X-Fields mask。掩码值是您要获取的逗号分隔变量列表。休息被忽略。
    • the blog 帖子中你链接的那个,你不喜欢... ;)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-04-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-05
      相关资源
      最近更新 更多