Search code examples
pythonflaskerror-handlinghttp-status-code-404blueprint

I tried using Blueprints for 404 error handling in Flask, but I do not seem to get it working. Here is my code:


errors/handlers.py

from flask import render_template
from autoapp import app
from dockblaster.errors import errors_blueprint


@app.errorhandler(404)
@errors_blueprint.app_errorhandler(404)
def not_found_error(error):
    return render_template('error_pages/page_not_found.html'), 404

errors/__init__.py:

from flask import Blueprint
errors_blueprint = Blueprint('errors', __name__)
import dockblaster.errors

I am finally registering the blueprint in app.py:

def create_app(config_object=ProdConfig):

"""An application factory, as explained here: http://flask.pocoo.org/docs/patterns/appfactories/.
:param config_object: The configuration object to use.
"""

app = Flask(__name__.split('.')[0])
app.config.from_object(config_object)

from dockblaster.errors import errors_blueprint
app.register_blueprint(errors_blueprint)

register_extensions(app)
register_blueprints(app)
return app

I do not seem to get this working, because the page that I have created for redirection of 404 errors isn't reachable with a blueprint for errors.


Solution

  • I was able to sort this out by myself.

    I did this:

    I removed the errors/handlers.py file, and added the code to errors/int.py thus avoiding another file import to access the blueprint handler for errors. This seemed to work for me.