"""JSON Draft4 Schema Validator Wrapper. A Wrapper for a JSON Draft4 schema validation library which allows us to transform the results into an internal Response() format. """ from functools import wraps from jsonschema import validate from jsonschema import ValidationError from oto import response from oto.adaptors.flask import flaskify from content_review.constants import error def validate_headers(request, schema): """Validate HTTP request headers decorator. Args: request (werkzeug.local.LocalProxy): request object from the handler. schema (Draft4Validator): the JSON Draft4 Schema to validate against. Returns: callable: the wrapped function. """ def wrap(fn): @wraps(fn) def wrapped_f(*args, **kwargs): try: validate(dict(request.headers), schema) except ValidationError as err: return flaskify( response.create_error_response( code=error.HEADER_VALIDATION_ERROR, message=str(err))) return fn(*args, **kwargs) return wrapped_f return wrap def validate_body(request, schema): """Validate HTTP request body decorator. Args: request (werkzeug.local.LocalProxy): request object from the handler. schema (Draft4Validator): the JSON Draft4 Schema to validate against. Returns: callable: the wrapped function. """ def wrap(fn): @wraps(fn) def wrapped_f(*args, **kwargs): try: validate(request.get_json(silent=True, force=True), schema) except ValidationError as err: return flaskify( response.create_error_response( code=error.BODY_VALIDATION_ERROR, message=str(err))) return fn(*args, **kwargs) return wrapped_f return wrap