Flask register_blueprint error (Python)
I just ran into this same issue with another application that I was refactoring to use blueprints. There's no need for a workaround, since Flask offers a decorator for just such a case: app_errorhandler
. It works exactly like errorhandler
in that it registers an error route for the entire app, but it works with blueprints. Like so:
from flask import render_templatefrom . import main @main.app_errorhandler(404)def page_not_found(e): return render_template('404.html'), 404@main.app_errorhandler(500)def internal_server_error(e): return render_template('500.html'), 500
Grinberg's book, Flask Web Development -- an excellent read -- uses this decorator for error pages registered on the main
blueprint. You can review the companion code here. I missed it at first, too. :P
You can't create a 500 handler on a blueprint.
https://www.bountysource.com/issues/1400879-can-not-register-a-500-error-handler-for-blueprint
You'll have to do it on the main application. I feel your pain though, since you have an app factory and no routes in app/__init__.py.
I usually do something like this in my app factory modules to handle this shortcoming:
def register_errorhandlers(app): def render_error(error): error_code = getattr(error, 'code', 500) return render_template("{0}.html".format(error_code)), error_code for errcode in [500]: app.errorhandler(errcode)(render_error) return None
and in create_app(config_name), app factory method, I call it:
register_errorhandlers(app)