"""JSON Draft3 Schema Validator Wrapper.""" from functools import wraps from jsonschema import FormatChecker, ValidationError, validate from oto import response from oto.adaptors.flask import flaskify as oto_flaskify from timed_release.constants import error 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(function): @wraps(function) def wrapped_f(*args, **kwargs): try: request_body = request.get_json(silent=True) or {} validate(request_body, schema, format_checker=FormatChecker()) except ValidationError as error_message: return oto_flaskify( response.create_error_response( code=error.ERROR_CODE_BODY_VALIDATION, message=str(error_message))) return function(*args, **kwargs) return wrapped_f return wrap