Can we have Flask error handlers in a separate module

We port our Flask application from function-based views to pluggable views, all working as expected, except for error handlers. I am trying to put all the error handlers in one module named error_handlers.py and import it into the main module. But that does not work. I tried a google search and found several Git repositories following the same method, but it does not work for me, please help me solve this problem.

app | |__ __init__.py |__ routing.py (which has the app=Flask(__name__) and imported error handlers here [import error_handlers]) |__ views.py |__ error_handlers.py (Ex: @app.errorhandler(FormDataException)def form_error(error):return jsonify({'error': error.get_message()}) |__ API (api modules) | | |__ __init__.py |__ user.py 

I am using Python 2.6 and Flask 0.10.1.

+6
source share
2 answers

I think you are importing the error_handlers module into routing.py as if

 import error_handlers 

You better import as below, as in routing.py

 from error_handlers import * 

This may help you :-)

0
source

For now, you can do this with circular imports , for example:

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 can be tricky in more complex scenarios.

Flask has a clean and flexible way to create applications from multiple modules, the blueprints concept. To register error handlers with flask.Blueprint , you can use any of these:

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 methods achieve the same, depending on what suits you.

+9
source

Source: https://habr.com/ru/post/972563/


All Articles