Python jsonschema.validators.validator_for() Examples

The following are code examples for showing how to use jsonschema.validators.validator_for(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: py-factom-did   Author: factomatic   File: schema.py    MIT License 6 votes vote down vote up
def get_schema_validator(schema_file, version=ENTRY_SCHEMA_V100):
    """Instantiates the jsonschema.Validator instance for the given schema and version

    Parameters
    ----------
    schema_file: str
        The filename of the JSON schema
    version: str, optional
        The version of the schema

    Returns
    -------
    jsonschema.Validator
        The validator instance for the given schema and version
    """
    schema = _load_json_schema(schema_file, version)
    cls = validator_for(schema)
    cls.check_schema(schema)
    return cls(schema) 
Example 2
Project: arche   Author: scrapinghub   File: schema.py    MIT License 6 votes vote down vote up
def full_validate(
    schema: RawSchema, raw_items: RawItems, keys: pd.Index
) -> Dict[str, set]:
    """This function uses jsonschema validator which returns all found error per item.
    See `fast_validate()` for arguments descriptions.
    """
    errors: DefaultDict = defaultdict(set)

    validator = validators.validator_for(schema)(schema)
    validator.format_checker = FormatChecker()
    for i, raw_item in enumerate(tqdm(raw_items, desc="JSON Schema Validation")):
        raw_item.pop("_type", None)
        raw_item.pop("_key", None)
        for e in validator.iter_errors(raw_item):
            error = format_validation_message(
                e.message, e.path, e.schema_path, e.validator
            )
            errors[error].add(keys[i])
    return dict(errors) 
Example 3
Project: wagtail-jsonschema-forms   Author: APSL   File: jsonschema_parser.py    MIT License 6 votes vote down vote up
def validate_json(json_form, schema, *args, **kwargs):
        """
        Function that validates the json recieved under the schema and returns a dict with the errors, if there are any
        :param json_form: dict
        :param schema: dict
        :return dict
        """
        cls = validator_for(schema)
        cls.check_schema(schema)
        json_errors = cls(schema, *args, **kwargs).iter_errors(json_form)
        errors = {}
        for error in json_errors:
            # errors can be from fields validation or required camps
            form_field = error.path[0] if error.path else error.validator_value[0]
            errors[form_field] = error.message
        return errors 
Example 4
Project: misp42splunk   Author: remg427   File: cli.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def parse_args(args):
    arguments = vars(parser.parse_args(args=args or ["--help"]))
    if arguments["validator"] is None:
        arguments["validator"] = validator_for(arguments["schema"])
    return arguments 
Example 5
Project: git_for_splunk   Author: ChrisYounger   File: cli.py    Apache License 2.0 5 votes vote down vote up
def parse_args(args):
    arguments = vars(parser.parse_args(args=args or ["--help"]))
    if arguments["validator"] is None:
        arguments["validator"] = validator_for(arguments["schema"])
    return arguments 
Example 6
Project: spidermon   Author: scrapinghub   File: validator.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _validate(self, data, strict=False):
        validator_cls = validator_for(self._schema)
        validator = validator_cls(schema=self._schema, format_checker=format_checker)
        errors = validator.iter_errors(data)

        for error in errors:
            absolute_path = list(error.absolute_path)
            required_match = REQUIRED_RE.search(error.message)
            if required_match:
                absolute_path.append(required_match.group(1))
            field_name = ".".join([str(p) for p in absolute_path])
            self._add_errors({field_name: [error.message]}) 
Example 7
Project: pyblish-rpc   Author: pyblish   File: cli.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def parse_args(args):
    arguments = vars(parser.parse_args(args=args or ["--help"]))
    if arguments["validator"] is None:
        arguments["validator"] = validator_for(arguments["schema"])
    return arguments 
Example 8
Project: pastebin2misp   Author: renzejongman   File: cli.py    MIT License 5 votes vote down vote up
def parse_args(args):
    arguments = vars(parser.parse_args(args=args or ["--help"]))
    if arguments["validator"] is None:
        arguments["validator"] = validator_for(arguments["schema"])
    return arguments 
Example 9
Project: TA-thehive   Author: remg427   File: cli.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def parse_args(args):
    arguments = vars(parser.parse_args(args=args or ["--help"]))
    if arguments["validator"] is None:
        arguments["validator"] = validator_for(arguments["schema"])
    return arguments 
Example 10
Project: accelerated-data-lake   Author: aws-samples   File: cli.py    Apache License 2.0 5 votes vote down vote up
def parse_args(args):
    arguments = vars(parser.parse_args(args=args or ["--help"]))
    if arguments["validator"] is None:
        arguments["validator"] = validator_for(arguments["schema"])
    return arguments 
Example 11
Project: TA-intezer   Author: secops4thewin   File: cli.py    MIT License 5 votes vote down vote up
def parse_args(args):
    arguments = vars(parser.parse_args(args=args or ["--help"]))
    if arguments["validator"] is None:
        arguments["validator"] = validator_for(arguments["schema"])
    return arguments 
Example 12
Project: Requester   Author: kylebebak   File: cli.py    MIT License 5 votes vote down vote up
def parse_args(args):
    arguments = vars(parser.parse_args(args=args or ["--help"]))
    if arguments["validator"] is None:
        arguments["validator"] = validator_for(arguments["schema"])
    return arguments 
Example 13
Project: airflowscan   Author: nightwatchcybersecurity   File: __init__.py    Apache License 2.0 5 votes vote down vote up
def validate(filename):
        """
        Validates provided JSON dictionary based on our schema

        :param filename: file to be validated
        :return: list of errors
        """

        # Load schema and initialize validator
        schema_data = Utils._load_schema()
        validator = validator_for(schema_data)

        # Read file, convert to a JSON dictionary and validate
        data = Utils._convert_config_file_to_json_dict(filename)
        errors = validator(schema=schema_data).iter_errors(data)

        # Convert errors to our own class
        data = []
        for error in errors:
            data.append(ValidationError(
                title=error.schema['title'],
                section=error.path[0],
                setting=error.path[1] if len(error.path) > 1 else None,
                message=error.message
            ))
        return data 
Example 14
Project: TA-securitytrails   Author: secops4thewin   File: cli.py    MIT License 5 votes vote down vote up
def parse_args(args):
    arguments = vars(parser.parse_args(args=args or ["--help"]))
    if arguments["validator"] is None:
        arguments["validator"] = validator_for(arguments["schema"])
    return arguments 
Example 15
Project: Pizza-or-Not-a-Pizza   Author: mraza007   File: cli.py    MIT License 5 votes vote down vote up
def parse_args(args):
    arguments = vars(parser.parse_args(args=args or ["--help"]))
    if arguments["validator"] is None:
        arguments["validator"] = validator_for(arguments["schema"])
    return arguments 
Example 16
Project: TA-bigfix   Author: jimmyatSplunk   File: cli.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def parse_args(args):
    arguments = vars(parser.parse_args(args=args or ["--help"]))
    if arguments["validator"] is None:
        arguments["validator"] = validator_for(arguments["schema"])
    return arguments 
Example 17
Project: flask-json-schema   Author: sanjeevan   File: __init__.py    MIT License 5 votes vote down vote up
def validate(self, schema, methods=None, format_checker=None):
        def wrapper(fn):
            @wraps(fn)
            def decorated(methods=None, format_checker=None, *args, **kwargs):
                validator_kwargs = {
                    'schema': schema,
                    'format_checker': format_checker if format_checker else self.config.get('JSON_SCHEMA_FORMAT_CHECKER')
                }

                # use default methods if not supplied as arguments to decorator
                if not methods:
                    methods = self.config.get('JSON_SCHEMA_METHODS')

                # check jsonschema
                if request.method in methods:
                    validator_cls = self.validator_cls if self.validator_cls else validator_for(schema)
                    validator = validator_cls(**validator_kwargs)
                    errors = list(validator.iter_errors(request.get_json()))
                    if errors:
                        raise JsonValidationError('Error validating against schema', errors)

                return fn(*args, **kwargs)

            # the wrapper() func ctx has access to format_checker & methods, but the decorator
            # won't, so we use partial, where those args are passed in
            pfunc = partial(decorated, format_checker=format_checker, methods=methods)

            # this is needed because partial() doesn't add in __name__ attribute to the created
            # partial function, which Flask requires
            update_wrapper(pfunc, decorated)

            return pfunc

        return wrapper 
Example 18
Project: notify-api   Author: alphagov   File: validators.py    MIT License 5 votes vote down vote up
def load_schemas(schemas_path, schema_names):
    loaded_schemas = {}
    for schema_name in schema_names:
        schema_path = os.path.join(schemas_path, '{}.json'.format(schema_name))

        with open(schema_path) as f:
            schema = json.load(f)
            validator = validator_for(schema)
            validator.check_schema(schema)
            loaded_schemas[schema_name] = schema
    return loaded_schemas 
Example 19
Project: notify-api   Author: alphagov   File: validators.py    MIT License 5 votes vote down vote up
def get_validator(schema_name):
    schema = _SCHEMAS[schema_name]
    return validator_for(schema)(schema, format_checker=FORMAT_CHECKER) 
Example 20
Project: StupidSimplePatchServer   Author: brysontyrrell   File: cli.py    MIT License 5 votes vote down vote up
def parse_args(args):
    arguments = vars(parser.parse_args(args=args or ["--help"]))
    if arguments["validator"] is None:
        arguments["validator"] = validator_for(arguments["schema"])
    return arguments 
Example 21
Project: StupidSimplePatchServer   Author: brysontyrrell   File: cli.py    MIT License 5 votes vote down vote up
def parse_args(args):
    arguments = vars(parser.parse_args(args=args or ["--help"]))
    if arguments["validator"] is None:
        arguments["validator"] = validator_for(arguments["schema"])
    return arguments 
Example 22
Project: SA-ctf_scoreboard   Author: splunk   File: cli.py    Creative Commons Zero v1.0 Universal 5 votes vote down vote up
def parse_args(args):
    arguments = vars(parser.parse_args(args=args or ["--help"]))
    if arguments["validator"] is None:
        arguments["validator"] = validator_for(arguments["schema"])
    return arguments 
Example 23
Project: tcrudge   Author: CodeTeam   File: handlers.py    MIT License 4 votes vote down vote up
def validate(self, data, schema, format_checker=None, **kwargs):
        """
        Method to validate parameters.
        Raises HTTPError(400) with error info for invalid data.

        :param data: bytes or dict
        :param schema: dict, valid JSON schema
          (http://json-schema.org/latest/json-schema-validation.html)
        :return: None if data is not valid. Else dict(data)
        """
        # Get and parse arguments
        if isinstance(data, dict):
            _data = data  # pragma: no cover
        else:
            try:
                _data = json.loads(data.decode())
            except ValueError as exc:
                # json.loads error
                raise HTTPError(
                    400,
                    body=self.get_response(
                        errors=[
                            {
                                'code': '',
                                'message': 'Request body is not a valid json object',
                                'detail': str(exc)
                            }
                        ]
                    )
                )
        v = validator_for(schema)(schema, format_checker=format_checker)
        errors = []
        for error in v.iter_errors(_data):
            # error is an instance of jsonschema.exceptions.ValidationError
            err_msg = xhtml_escape(error.message)
            errors.append({'code': '',
                           'message': 'Validation failed',
                           'detail': err_msg})
        if errors:
            # data does not pass validation
            raise HTTPError(400, body=self.get_response(errors=errors))
        return _data