简体   繁体   中英

Python Flask - Both json and html 404 error

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.

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]})

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)

However, now all error return the json, rather than only the api error.

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.

I put my API in it's own blueprint, and there I can define an errorhandler for that blueprint alone.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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