如何在flask_restplus中返回带有多个marshal_with()的响应? [英] How to return a response with multiple marshal_with() in flask_restplus?

查看:65
本文介绍了如何在flask_restplus中返回带有多个marshal_with()的响应?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Following is flask_restplus response call for PUT verb

@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

I'm making use of the @api.errorhandler But I don't know how to return multiple response format with marshal_with

推荐答案

好的旧答案只是将其列为Swagger中的有效响应.

Ok old answer just lists it as a valid response in Swagger.

但是使用本文 https://github.com/noirbizarre/flask-restplus/issues/559 我仍然有解决方案:

But with this article https://github.com/noirbizarre/flask-restplus/issues/559 I still got the solution:

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_restplus中返回带有多个marshal_with()的响应?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆