简体   繁体   English

如何从 flask 错误处理程序返回 json 响应?

[英]How to return a json response from a flask error handler?

I have a Flask app where I register an error as:我有一个 Flask 应用程序,我在其中注册了一个错误:

app.register_error_handler(401, handle_errors)

and my handle_errors function looks like this:我的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

However, when I invoke my API my response looks like this:但是,当我调用 API 时,我的响应如下所示:

< HTTP/1.0 401 UNAUTHORIZED
< Content-Type: text/html; charset=utf-8
...

Why does it return it as text/html even though I set the content_type to application/json ?为什么即使我将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.

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