"""JSON Draft3 Schema Validator Wrapper. A Wrapper for a JSON Draft3 schema validation library which allows us to transform the results into an internal Response() format. """ from images import response from images.constants import errors as error_constants def _filter(data): """Sanitize a dictionary of request input data. Sanitize a dictionary of request input data. (e.g. headers or body) before applying JSON schema validations to it. This includes: 1.) Stripping leading or trailing space from strings. 2.) Replacing empty strings with None. Args: data (dict): the data to be sanitized. Returns: dict: a sanitized version of the given data """ for key, value in data.items(): if isinstance(value, str): data[key] = value.strip() if data[key] == '': data[key] = None return data def validate(data, validator, failure_status=400): """Generic JSON Draft3 Schema Vaidation. Args: data (dict): the JSON to be validated. schema (Draft3Validator): the JSON Draft3 Schema to validate against. Returns: Response: the response of the create operation. """ errors = {} data = _filter(data) for error in sorted(validator.iter_errors(data), key=str): if error.relative_path: errors[error.relative_path.pop()] = error.message elif error.absolute_schema_path: errors[error.absolute_schema_path.pop()] = error.message if errors: return response.create_error_response( code=error_constants.VALIDATION_ERROR, message=errors, status=failure_status) return response.Response(message={'status': 'ok'}, status=200)