如何在flask_restplus中返回带有多个marshal_with()的响应?

时间:2019-05-29 16:02:10

标签: flask flask-restplus

以下是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返回多种响应格式

1 个答案:

答案 0 :(得分:2)

编辑:好的旧答案只是将其列为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