Created
September 20, 2016 04:44
-
-
Save jmvrbanac/679ff00d3176de04cc3948fa00adbd26 to your computer and use it in GitHub Desktop.
Example JSON Parse and Validation Decorator for Falcon
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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