flask: Allow blueprint-local routing for errorhandlers

The comment in flask.Blueprint.errorhandler notes, “Please be aware that routing does not happen local to a blueprint so an error handler for 404 usually is not handled by a blueprint unless it is caused inside a view function.”

Please add Blueprint-local routing for errors triggered by any request to an endpoint defined by a blueprint.

About this issue

  • Original URL
  • State: closed
  • Created 12 years ago
  • Comments: 17 (11 by maintainers)

Most upvoted comments

This came up in a recent Stack Overflow question. I mentioned this issue and answered with a workaround that routes to blueprint handlers from the top level handler based on request.path and Blueprint.url_prefix.

from flask import request, render_template

@app.errorhandler(404)
def handle_404(e):
    path = request.path

    # go through each blueprint to find the prefix that matches the path
    # can't use request.blueprint since the routing didn't match anything
    for bp_name, bp in app.blueprints.items():
        if path.startswith(bp.url_prefix):
            # get the 404 handler registered by the blueprint
            handler = app.error_handler_spec.get(bp_name, {}).get(404)

            if handler is not None:
                # if a handler was found, return it's response
                return handler(e)

    # return a default response
    return render_template('404.html'), 404