Python Flask - json and html error 404

I am making a small web interface running on a raspberry pi at home. It hosts some REST api as well as some web pages.

I am using Flask and have a route '/'

for index and some routes for 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 it abort(404)

returns an html error page which is fine for normal pages, but I would like to return json when a non-existent task is requested.

So, I have overridden the error handler:

@app.errorhandler(404)
def not_found(error):
    return make_response(jsonify({'error': 'Not found'}), 404)

      

However, now the whole error is returning json, not just the api error.

So my question is, how can I make the failed API requests return a json error, but other errors on the default html page?

+3


source to share


1 answer


The best way to find this is to use blueprints.

I have put my API in my own project and there I can define an error handler for just this drawing.



The only problem is that when there are nonexistent pages in the api, it uses the default error handler, not the one I defined for the api plan. There is a workaround for this as well, but this limitation of Flaza is apparently not big.

0


source







All Articles