【问题标题】:How to use Marshmallow Schema in Flask-restx Swagger UI Automatically如何在 Flask-restx Swagger UI 中自动使用 Marshmallow Schema
【发布时间】:2021-10-30 11:14:08
【问题描述】:

我正在尝试使用 flask-restx 和 marshmallow 创建一个宁静的网络服务。

我正在使用 marshmallow 进行请求和响应验证。

由于flask-restx api docs不支持swagger ui中的棉花糖模式,我想使用doc装饰器添加它。

控制器代码:

@ns.route('/')
class Test(Resource):
    @ns.doc(params={'test': 'test'})
    def get(self):
        _input_schema = MySchema()
        errors = _input_schema.validate(request.args)
        if errors:
            return Response(str(errors), status=400)
        other_things()

架构代码:

class MySchema(Schema):
    title = fields.Str()
    id = fields.Integer()
    slug = fields.Str()

我正在尝试自动将参数从架构添加到 api 文档中

@ns.doc(params=MySchema.ReturnAFieldDict())

它会给出类似的东西

@ns.doc(params={"title":"A string", "id": "Int value with min and max", "slug":"A str"})

有什么办法吗?

【问题讨论】:

    标签: flask swagger-ui marshmallow flask-restx


    【解决方案1】:

    您可以使用 api.marshal_with 来记录响应

    from flask_restx.fields import Integer, String
    test_get = api.model(
        "TestGet",
        {
            "name": String(required=True),
            "age": Integer(required=True),
        },
    )
    @api.marshal_with(schema.test_get, code=200)
    def get(self):
        return {"name": "test", "age": 123}
    

    marshal_with 映射返回的字典或对象,并根据模式映射字段。在这里,在这种情况下,返回的字典将映射到 test_get 模式,其中名称将为“test”,年龄将为 123。

    【讨论】:

    • 正如目前所写,您的答案尚不清楚。请edit 添加其他详细信息,以帮助其他人了解这如何解决所提出的问题。你可以找到更多关于如何写好答案的信息in the help center
    • 虽然此代码可能会回答问题,但提供有关它如何和/或为什么解决问题的额外上下文将提高​​答案的长期价值。
    【解决方案2】:

    我发现获取文档的一种方法是使用 @api.expect(schema) 装饰器。

    【讨论】:

    • 正如目前所写,您的答案尚不清楚。请edit 添加其他详细信息,以帮助其他人了解这如何解决所提出的问题。你可以找到更多关于如何写好答案的信息in the help center
    猜你喜欢
    • 1970-01-01
    • 2022-12-15
    • 1970-01-01
    • 2021-11-05
    • 2021-09-16
    • 1970-01-01
    • 2023-01-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多