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
To use any Flask Blueprint, you have to import it and then register it in the application using register_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.
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.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With