Flask – Custom 404 handling

If you’re using blueprint, and custom configuration for the routing, here is the place you can register your 404 handling.

__init__.py

import os

# Import flask and template operators
from flask import Flask, render_template
# Import SQLAlchemy
from flask_sqlalchemy import SQLAlchemy


# Define the database object which is imported
# by modules and views
db = SQLAlchemy()

""" Create an application instance """
def create_app(config_name):
    # Define the WSGI application object
    app = Flask(__name__)

    # Import configuration
    cfg = os.path.join(os.getcwd(), 'config', config_name + '.py')
    print(' * Configuration path "{0}"'.format(cfg))
    app.config.from_pyfile(cfg)

    # Initialize extensions
    db = SQLAlchemy(app)

    # Import a module / component using its blueprint handler variable (mod_auth)
    # from app.mod_auth.controllers import mod_auth as auth_module
    from .abc import abc as abc_blueprint
    from .xyz import xyz  as xyz_blueprint
   
    # Register blueprint(s)
    # app.register_blueprint(abc_module)
    # app.register_blueprint(xyz_module)
    # ..

    @app.errorhandler(500)
    def internal_server_error(e):
        return render_template('500.html'), 500  # Internal Server Error

    @app.errorhandler(404)
    def not_found(e):
        return render_template('404.html'), 404

    return app

## Staging Server Mode ##
config_name = os.environ.get('FLASK_CONFIG') or 'staging'
print(' * Loading configuration "{0}"'.format(config_name))
app = create_app(config_name)

 

Flask – Custom 404 handling

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.