Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can we have Flask error handlers in separate module

Tags:

python

flask

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 single module called error_handlers.py and importing it in to the main module. But it is not working. Tried searching in Google and find some Git repos following the same way, but it is not working for me, please help me to solve this issue.

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.

like image 294
John Prawyn Avatar asked Jul 21 '14 06:07

John Prawyn


1 Answers

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.

like image 166
famousgarkin Avatar answered Sep 20 '22 12:09

famousgarkin