Skip to content

Instantly share code, notes, and snippets.

@jmvrbanac
Created September 20, 2016 04:44
Show Gist options
  • Save jmvrbanac/679ff00d3176de04cc3948fa00adbd26 to your computer and use it in GitHub Desktop.
Save jmvrbanac/679ff00d3176de04cc3948fa00adbd26 to your computer and use it in GitHub Desktop.
Example JSON Parse and Validation Decorator for Falcon
def validate(schema):
def decorator(func):
def wrapper(self, req, resp, *args, **kwargs):
try:
raw_json = req.stream.read()
obj = json.loads(raw_json.decode('utf-8'))
except Exception:
raise falcon.HTTPBadRequest(
'Invalid data',
'Could not properly parse the provided data as JSON'
)
try:
jsonschema.validate(obj, schema)
except jsonschema.ValidationError as e:
raise falcon.HTTPBadRequest(
'Failed data validation',
e.message
)
return func(self, req, resp, *args, parsed=obj, **kwargs)
return wrapper
return decorator
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment