【问题标题】:How to return a response with multiple marshal_with() in flask_restplus?如何在 flask_restplus 中返回具有多个 marshal_with() 的响应?
【发布时间】:2020-05-05 08:35:15
【问题描述】:

以下是 flask_restplus 对 PUT 动词的响应调用

@api.doc('update a franchise by id')
    @api.expect(create_item_fields, validate=True)
    @api.marshal_with(success_fields)
    def put(self, fid):
        franchise = FranchiseModel.query.filter_by(id=fid).first()
        if franchise:
            is_success, result = FranchiseModel.update_franchise(
                franchise, api.payload)
            if is_success:
                return {'success': True, 'message': 'Franchise has been updated', 'data': result}, 200
            else:
                raise CouldNotUpdateFranchise(str(result))

@api.errorhandler(CouldNotUpdateFranchise)
    @api.marshal_with(error_fields)
    def return_error(error):
        return {'success': False, 'message': str(error)}, 400

我正在使用@api.errorhandler 但我不知道如何使用marshal_with 返回多响应格式

【问题讨论】:

    标签: flask flask-restplus


    【解决方案1】:

    编辑:好的旧答案只是将其列为 Swagger 中的有效响应。

    但是有了这篇文章https://github.com/noirbizarre/flask-restplus/issues/559我还是得到了解决方案:

    from flask_restplus import marshal
    # I call API 'foo' and my Namespace 'bar'
    another = foo.model('For 200', {'Another': fields.Integer()})
    success = foo.model('For 201', {'Success': fields.Integer()})
    
    @bar.route('/test/<int:id>')
    class Test(Resource):
        @bar.response(model=another, code=200)
        @bar.response(model=success, code=201)
        def get(self, id):
            if id == 200:
                 return marshal({'Another': 200}, another), 200
            elif id == 201:
                 return marshal({'Success': 201}, success), 201
    

    【讨论】:

    • 我希望你能得到我想说的……这里有点晚了……
    • 虽然已经有一段时间了,但我必须说这很有效,并且实际上对我有所帮助,即使现在使用flask-restx,因为不再维护flask-restplus
    • 是的,我实际上也在使用flask-restx,但是当我写这个答案时,它适用于两个平台:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多