简体   繁体   English

Content-Type 请求 header 错误处理未正确返回

[英]Content-Type request header error handling not returning correctly

I created a Flask error handler which will return 415 if Content-Type is not application/json.我创建了一个 Flask 错误处理程序,如果 Content-Type 不是 application/json,它将返回 415。 However, even if I selected an incorrect Content-Type in my Postman tool, I still get 200 response when it should return an error message.但是,即使我在 Postman 工具中选择了不正确的 Content-Type,当它应该返回错误消息时,我仍然会收到 200 响应。 What could be the problem?可能是什么问题呢?

Here is my code in app.py这是我在 app.py 中的代码

from flask import Flask, make_response, jsonify, request

app = Flask(__name__)

@app.errorhandler(415)
def unsupported_media(error):
    content_type = request.content_type('Content-Type')
    if 'Content-Type' in request.headers and content_type != 'application/json':
        return make_response(jsonify(error = 'Content-Type is required to be application/json'), 415)

I also setup incorrect Content-Type value in my postman我还在我的 postman 中设置了不正确的 Content-Type 值

errorhandler Register a function to handle errors by code or exception class. errorhandler注册一个 function 以通过代码或异常 class 处理错误。

Maybe before_request is what you need.也许before_request是你需要的。

from flask import Flask, request, abort


app = Flask(__name__)

# This will register the validate function to all the endpoint
@app.before_request
def _is_json():
    if not request.is_json:
        abort(415, 'Content-Type is required to be application/json')

@app.errorhandler(415)
def unsupported_media(error):
    return {'error': error.description}

"""
YOUR router view functions or classes
"""

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM