Kin*_*aro 7 flask flask-restful
我正在做一个简单的 Flask REST API 测试,例如当我调用 {{url}}/items 时,我得到了项目列表。但是,如果调用传递到不存在的端点,例如 {{url}}/itemsss,那么我会在 html 中收到错误 404。
我想让错误处理更加友好,并针对某些错误(例如 400、404,405...)返回 json 而不是 html。
例如,对于 404,我试过这个:
@app.errorhandler(404)
def not_found(e):
response = jsonify({'status': 404,'error': 'not found',
'message': 'invalid resource URI'})
response.status_code = 404
return response
Run Code Online (Sandbox Code Playgroud)
但是它不起作用。
我的问题与此类似:Python Flask - json 和 html 404 错误
我想知道,如果使用蓝图是实现这一目标的唯一方法吗?
如果有更简单的方法将 404 错误输出为 json?
例如,而不是这样:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<title>404 Not Found</title>
<h1>Not Found</h1>
<p>The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again.</p>
Run Code Online (Sandbox Code Playgroud)
像这样的东西:
{
error: true,
status: 404,
code: "error.notFound",
message: "API endpoint not found",
data: { }
}
Run Code Online (Sandbox Code Playgroud)
感谢您对此的帮助。
通常,当我需要返回自定义错误消息时,Flask-RESTful我会执行以下操作:
from flask import make_response, jsonify
def custom_error(message, status_code):
return make_response(jsonify(message), status_code)
Run Code Online (Sandbox Code Playgroud)
我想我在官方文档中找到了解决方案:
from flask import json
from werkzeug.exceptions import HTTPException
@app.errorhandler(HTTPException)
def handle_exception(e):
"""Return JSON instead of HTML for HTTP errors."""
# start with the correct headers and status code from the error
response = e.get_response()
# replace the body with JSON
response.data = json.dumps({
"code": e.code,
"name": e.name,
"description": e.description,
})
response.content_type = "application/json"
return response
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5381 次 |
| 最近记录: |