我正在做一个简单的 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 …Run Code Online (Sandbox Code Playgroud)