Flask JSON自定义错误页面
在Flask中,有没有关于使用JSON作为自定义错误页面的实现呢?
1 个回答
30
你可以使用Flask中的“jsonify”这个助手来创建一个json格式的响应对象,然后在返回之前设置这个响应的状态码,方法如下:
def not_found(error):
response = jsonify({'code': 404,'message': 'No interface defined for URL'})
response.status_code = 404
return response
你可以通过把这个函数包裹在错误处理器中来注册它作为处理函数:
@app.errorhandler(404)
def not_found(error):
...
或者,直接在错误处理规范上设置它:
app.error_handler_spec[None][404] = not_found