Skip to content

Instantly share code, notes, and snippets.

@joshfriend
Created May 25, 2016 20:18
Show Gist options
  • Save joshfriend/8c08422953777cca810bcbb9f7212fc0 to your computer and use it in GitHub Desktop.
Save joshfriend/8c08422953777cca810bcbb9f7212fc0 to your computer and use it in GitHub Desktop.
Flask Error Handlers
#!/usr/bin/env python
from flask import jsonify, current_app
from werkzeug.datastructures import WWWAuthenticate
from werkzeug.http import HTTP_STATUS_CODES
from flask_principal import PermissionDenied
def _make_errorhandler(code):
def errorhandler(e):
return jsonify({
'message': HTTP_STATUS_CODES[code],
'status': code,
}), code
return errorhandler
def unauthorized(e):
data, status = _make_errorhandler(401)(e)
r = Response('')
www_auth = WWWAuthenticate()
www_auth.type = 'Bearer'
www_auth.realm = current_app.config['APP_NAME']
headers = {
'WWW-Authenticate': www_auth.to_header(),
}
return data, status, headers
def unprocessable_entity(e):
try:
messages = e.data['exc'].messages
except Exception: # pragma: no cover
messages = ['Invalid Request']
return jsonify({
'messages': messages,
'status': 422
}), 422
# Install default handlers
handler_map = {
code: _make_errorhandler(code) for code in HTTP_STATUS_CODES.iterkeys()
}
handler_map[401] = unauthorized
handler_map[422] = unprocessable_entity
handler_map[PermissionDenied] = handler_map[403]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment