Sure there is, but you need to parameterise the registrations.
Instead of using decorators, move the registration to a function:
def page_not_found(e):
return jsonify({'status': 'error',
'reason': '''There's no API call for %s''' % request.base_url,
'code': 404}), 404
def register_all(app):
app.register_error_handler(404, page_not_found)
then import register_all
and call it with your Flask()
object.
This uses the Flask.register_error_handler()
function instead of the decorator.
To support blueprints too, you'll need to wait for a next release of Flask (one including this commit), or use the decorator function directly:
app_or_blueprint.errorhandler(404)(page_not_found)
For a lot of these tasks, you can use a Blueprint as well, provided you use Blueprint.app_errorhandler()
:
common_errors = Blueprint('common_errors')
@common_errors.errorhandler(404)
def page_not_found(e):
return jsonify({'status': 'error',
'reason': '''There's no API call for %s''' % request.base_url,
'code': 404}), 404
Not everything can be handled by a Blueprint, but if all you are registering is error handlers, a Blueprint is a good approach.
Import the blueprint as usual and register it to your app:
from yourmodule import common_errors
app.register_blueprint(common_errors)