Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

flask: error_handler for blueprints

Can error_handler be set for a blueprint?

@blueprint.errorhandler(404) def page_not_found(error):     return 'This page does not exist', 404 

edit:

https://github.com/mitsuhiko/flask/blob/18413ed1bf08261acf6d40f8ba65a98ae586bb29/flask/blueprints.py

you can specify an app wide and a blueprint local error_handler

like image 710
blueblank Avatar asked Oct 07 '12 12:10

blueblank


People also ask

How do I run a flask app with blueprints?

To use any Flask Blueprint, you have to import it and then register it in the application using register_blueprint() .

What is the point of flask blueprint?

A Flask blueprint helps you to create reusable instances of your application. It does so by organizing your project in modules. Those modules are then registered the main application. They help in creating an application factory.

How do you handle exceptions in flask?

Flask gives you the ability to raise any HTTP exception registered by Werkzeug. However, the default HTTP exceptions return simple exception pages. You might want to show custom error pages to the user when an error occurs. This can be done by registering error handlers.


2 Answers

You can use Blueprint.app_errorhandler method like this:

bp = Blueprint('errors', __name__)  @bp.app_errorhandler(404) def handle_404(err):     return render_template('404.html'), 404  @bp.app_errorhandler(500) def handle_500(err):     return render_template('500.html'), 500 
like image 184
suzanshakya Avatar answered Oct 09 '22 20:10

suzanshakya


errorhandler is a method inherited from Flask, not Blueprint. If you are using Blueprint, the equivalent is app_errorhandler.

The documentation suggests the following approach:

def app_errorhandler(self, code):         """Like :meth:`Flask.errorhandler` but for a blueprint.  This         handler is used for all requests, even if outside of the blueprint.         """ 

Therefore, this should work:

from flask import Blueprint, render_template  USER = Blueprint('user', __name__)  @USER.app_errorhandler(404) def page_not_found(e):     """ Return error 404 """     return render_template('404.html'), 404 

On the other hand, while the approach below did not raise any error for me, it didn't work:

from flask import Blueprint, render_template  USER = Blueprint('user', __name__)  @USER.errorhandler(404) def page_not_found(e):     """ Return error 404 """     return render_template('404.html'), 404 
like image 39
T. Goncalves Avatar answered Oct 09 '22 20:10

T. Goncalves