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