def validate_json_request(required_fields):
def decorator(func):<EOL><INDENT>@wraps(func)<EOL>def wrapped_func(request, *args, **kwargs):<EOL><INDENT>try:<EOL><INDENT>request_dict = json.loads(request.raw_post_data)<EOL><DEDENT>except ValueError as e:<EOL><INDENT>return JsonResponseBadRequest('<STR_LIT>' % e)<EOL><DEDENT>for k in required_fields:<EOL><INDENT>if k not in request_dict:<EOL><INDENT>return JsonResponseBadRequest(<EOL>'<STR_LIT>' % k)<EOL><DEDENT><DEDENT>return func(request, request_dict, *args, **kwargs)<EOL><DEDENT>return wrapped_func<EOL><DEDENT>return decorator<EOL>
Return a decorator that ensures that the request passed to the view
function/method has a valid JSON request body with the given required
fields.  The dict parsed from the JSON is then passed as the second
argument to the decorated function/method.  For example:

@json_request({'name', 'date'})
def view_func(request, request_dict):
    ...