【发布时间】:2022-01-24 03:29:09
【问题描述】:
我创建了一个 Flask 错误处理程序,如果 Content-Type 不是 application/json,它将返回 415。但是,即使我在 Postman 工具中选择了不正确的 Content-Type,当它应该返回错误消息时,我仍然会收到 200 响应。可能是什么问题?
这是我在 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)
我还在邮递员中设置了错误的 Content-Type 值
更新: 我尝试了这段代码,它奏效了。但是,我不确定这是否是正确的实现。我还应该使用 app.errorhandler() 吗?
@app.before_request
def unsupported_media():
if not request.is_json:
return jsonify(Error = 'Content-Type is required to be application/json'), 415
【问题讨论】:
-
也尝试添加
else语句。