[英]How to return a json response from a flask error handler?
我有一個 Flask 應用程序,我在其中注冊了一個錯誤:
app.register_error_handler(401, handle_errors)
我的handle_errors
function 看起來像這樣:
def handle_errors(error):
response = make_response()
response.data = str(error.to_dict())
response.content_type = "application/json"
response.status_code = 401
return response, response.status_code
但是,當我調用 API 時,我的響應如下所示:
< HTTP/1.0 401 UNAUTHORIZED
< Content-Type: text/html; charset=utf-8
...
為什么即使我將content_type
設置為application/json
,它仍將其作為text/html
返回?
import json
from flask import Flask, Response, abort
app = Flask(__name__)
app.config['PROPAGATE_EXCEPTIONS'] = True
#register 500 error handler
@app.errorhandler(Exception)
# handle all other exception
def all_exception_handler(error):
res = {"error": str(error)}
return Response(status=500, mimetype="application/json", response=json.dumps(res))
# handle 401 exception
def error_401_handler(error):
res = {"error": "Unauthorized"}
return Response(status=401, mimetype="application/json", response=json.dumps(res))
# test exception 500 with http get
@app.route("/test500")
def test500():
raise Exception("test exception")
# test exception 401 with http get
@app.route("/test401")
def test401():
abort(401)
# register 401 error handler
app.register_error_handler(401, error_401_handler)
app.run(host="0.0.0.0")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.