Can we have Flask error handlers in separate module

While you can do this using some circular imports, e.g.:

app.py

import flask

app = flask.Flask(__name__)

import error_handlers

error_handlers.py

from app import app

@app.errorhandler(404)
def handle404(e):
    return '404 handled'

Apparently, this may get tricky in more complex scenarios.

Flask has a clean and flexible way to compose an applications from multiple modules, a concept of blueprints. To register error handlers using a flask.Blueprint you can use either of these:

  • flask.Blueprint.errorhandler decorator to handle local blueprint errors

  • flask.Blueprint.app_errorhandler decorator to handle global app errors.

Example:

error_handlers.py

import flask

blueprint = flask.Blueprint('error_handlers', __name__)

@blueprint.app_errorhandler(404)
def handle404(e):
    return '404 handled'

app.py

import flask
import error_handlers

app = flask.Flask(__name__)
app.register_blueprint(error_handlers.blueprint)

Both ways achieve the same, depends what suits you better.

Tags:

Python

Flask