Skip to content

Instantly share code, notes, and snippets.

@zopyx
Created April 19, 2013 13:49
Show Gist options
  • Save zopyx/5420477 to your computer and use it in GitHub Desktop.
Save zopyx/5420477 to your computer and use it in GitHub Desktop.
from functools import wraps
import json
from pyramid.httpexceptions import HTTPBadRequest
import validictory
def validate_json(inbound_schema=None, outbound_schema=None):
"""
Validate the request's JSON input and output using JSON schemas
Based on http://www.alexconrad.org/2013/02/loggingexception.html.
Return ``HTTPBadRequest`` on error.
It will ensure:
- request Content-Type is ``application/json``
- JSON input (request.body) validates against the given JSON ``inbound_schema``
and output validates against the given JSON ``outbound_schema``
- provide the parsed JSON data through ``request.json``
"""
def decorator(func):
@wraps(func)
def wrapper(view):
request = view.request
error = None
if inbound_schema:
try:
if request.environ['CONTENT_TYPE'] != 'application/json':
msg = 'Request Content-Type must be application/json'
raise ValueError(msg)
data = json.loads(unicode(request.body))
validictory.validate(data, inbound_schema)
except ValueError as err:
error = {'error': str(err)}
except validictory.ValidationError as err:
error = {'error': "Invalid JSON: %s" % err}
if error is not None:
return HTTPBadRequest(body=json.dumps(error),
content_type='application/json')
view.request.json = data
result = func(view)
if outbound_schema:
validictory.validate(result, outbound_schema)
return result
return wrapper
return decorator
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment