Can we have Flask error handlers in separate module

前端 未结 3 1010
栀梦
栀梦 2021-02-08 04:24

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

3条回答
  •  自闭症患者
    2021-02-08 04:39

    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.

提交回复
热议问题