from functools import wraps from jsonschema import validate from jsonschema import ValidationError from oto import response from oto.adaptors.flask import flaskify as oto_flaskify from masters_registry.constant import error def validate_headers(request, schema): """A decorator to call when validating HTTP request headers. 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: validate(dict(request.headers), schema) except ValidationError as err: return oto_flaskify( response.create_error_response( code=error.HEADER_VALIDATION_ERROR, message=str(err))) return function(*args, **kwargs) return wrapped_f return wrap def validate_body(request, schema): """A decorator to call when validating HTTP request body. 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: validate(request.get_json(), schema) except ValidationError as err: return oto_flaskify( response.create_error_response( code=error.BODY_VALIDATION_ERROR, message=str(err))) return function(*args, **kwargs) return wrapped_f return wrap