Python Flask-json和html 404错误 [英] Python Flask - Both json and html 404 error
问题描述
我正在制作一个小的Web界面,该界面在家里的树莓派上运行.它托管了一些REST api和一些网页.
I'm making a small web interface running on a raspberry pi at home. It hosts a little REST api as well as some web pages.
我正在使用Flask,并为索引设置了路由'/'
,并为REST api提供了一些路由'/api/v1.0/tasks'
.
I'm using Flask, and have a route '/'
for the index, and some routes for the REST api '/api/v1.0/tasks'
.
@app.route('/')
def index():
return render_template('index.html')
@app.route('/gnodes/api/v1.0/tasks', methods=['GET'])
def get_tasks():
return jsonify({'tasks': tasks})
@app.route('/gnodes/api/v1.0/tasks/<int:task_id>', methods=['GET'])
def get_task(task_id):
task = [task for task in tasks if task['id'] == task_id]
if not task:
abort(404)
return jsonify({'task': task[0]})
但是, abort(404)
返回一个html错误页面,这对于普通页面来说很好,但是我想在请求不存在的任务时返回一个json.
However, abort(404)
returns a html error page, which is fine for normal pages, but I wanted to return a json when a non-existing task is requested.
所以我已经改写了错误处理程序:
So I've overridden the errorhandler:
@app.errorhandler(404)
def not_found(error):
return make_response(jsonify({'error': 'Not found'}), 404)
但是,现在所有错误都返回json,而不仅是api错误.
However, now all error return the json, rather than only the api error.
所以我的问题是,如何对API发出失败的请求会返回json错误,而其他错误则是默认的html错误页面?
So my question, how can I make failed requests to the API return the json error, but other errors the default html error page?
推荐答案
我发现解决此问题的最佳方法是使用蓝图.
The best way I found to fix this is using blueprints.
我将自己的API放入了自己的蓝图中,在那里我可以单独为该蓝图定义一个错误处理程序.
I put my API in it's own blueprint, and there I can define an errorhandler for that blueprint alone.
唯一的问题是,当api中不存在页面时,将使用默认的错误处理程序,而不是我为api蓝图定义的页面.对此也有一些解决方法,但这显然是Flask的局限性,没有大碍之处.
The only problem is that when there are non-existing pages in the api the default errorhandler is used, rather than the one I defined for the api-blueprint. There are some workaround for that too, but this is a limitation of Flask aparently, no biggy.
这篇关于Python Flask-json和html 404错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!