We are migrating our Flask app from function based views to pluggable views, all working as expected, except the error handlers. I am trying to put all the error handlers in a s
@NaturalBornCamper said that he was getting errors. I had to google around a bit but this is what I ended up with for now. I tried to reply to his comment but I did not have enough reputation.
My solution followed the blueprints path and having each blueprint have its own templates and static folder as well.
I have it under src/app/blueprints/errors/handlers.py
from flask import Blueprint
bp = Blueprint('errors',
__name__,
template_folder='templates',
static_folder='static', )
@bp.app_errorhandler(404)
def handle404(error):
return '404 handled'
With the following in my init at src/app/blueprints/errors/__init__.py
:
from .handlers import bp as errors_bp
If you want your blueprint to handle its own errors you would do:
@bp.errorhandler()
But from my understanding this won't catch some errors because blueprints routes are registered differently so it might behave differently then you expect.
This is what I have as the factory application under src/app/__init__.py
from flask import Flask
def create_app():
from app.blueprints.personal import personal_bp
from app.blueprints.errors import errors_bp
app = Flask(__name__, instance_relative_config=True)
app.register_blueprint(personal_bp, url_prefix='/') # blueprint for my personal site set to the default route
app.register_blueprint(errors_bp)
return app
Then I run the following command to test with it flask from /src
:
> export FLASK_APP=app
> export FLASK_APP=development
> flask run