我想检查请求是否已使用Flask-RestPlus提供了所需的标头。
我尝试使用https://flask-restful.readthedocs.io/en/0.3.5/reqparse.html,我之前使用它来检查正文是否有必需的参数,并且可以正常工作,但我还需要检查标题
def RequestParser():
parser = reqparse.RequestParser()
parser.add_argument('PaymentMethod', location='headers')
return parser
@api.route('/request')
class Request(Resource):
parser = RequestParser()
def post(self):
data = self.parser.parse_args()
paymentMethod = request.headers.get('PaymentMethod')
paymentEndpoint = request.headers.get('PaymentEndpoint')
return paymentMethod
我希望结果会告诉我,当主体中缺少参数时,缺少标头也需要相同的结果。
答案 0 :(得分:1)
尝试添加参数required
:
parser.add_argument('PaymentMethod', required=True, location='headers')
请参考:https://flask-restful.readthedocs.io/en/0.3.5/reqparse.html#required-arguments
答案 1 :(得分:0)
我将expect
装饰器与parser
一起使用,它检查了user_id header
。
app = Flask(__name__)
api = Api(app, authorizations=authorizations, security=[{"browser": ["ui"]}])
# Swagger namespaces - in Java they are controllers.
word_count_ns = api.namespace(name='Word count', path='/', description='Word count')
user_id_header_parser = api.parser()
user_id_header_parser.add_argument('user_id', location='headers')
@api.expect(user_id_header_parser)
@word_count_ns.route(api_word_count)
class WordCounter(Resource):
def post(self):
"""Counts words in request text. Expects header user_id"""
user_input = request.data.decode()
user_id_header = request.headers.get('user_id')
if not check_exists_by_id(user_id_header):
return Response('user_id header is needed', 401)
return return Response('[]', mimetype='application/json;charset=UTF-8')