当前位置: 首页>>代码示例>>Python>>正文


Python jsonschema.Draft4Validator类代码示例

本文整理汇总了Python中jsonschema.Draft4Validator的典型用法代码示例。如果您正苦于以下问题:Python Draft4Validator类的具体用法?Python Draft4Validator怎么用?Python Draft4Validator使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了Draft4Validator类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: __init__

    def __init__(self, json_data, strict=False, live_schema=None):
        self.live_schema = live_schema
        if not hasattr(json_data, '__getitem__'):
            raise TypeError('json_data must be a dict.')
        if (not self.schema) and (live_schema is None):
            raise NotImplementedError('schema not implemented!')
        if live_schema is not None:
            if not self.schema:
                self.schema = live_schema
            else:
                self.schema['properties'].update(live_schema['properties'])
                if "required" in self.schema and "required" in live_schema:
                    self.schema['required'] = list(
                        set(self.schema['required']) |
                        set(live_schema["required"])
                    )

        Draft4Validator.check_schema(self.schema)

        self.data = {}
        if not strict:
            self._filter_data(json_data, self.schema['properties'], self.data)
        else:
            self.data = json_data
        self.validator = Draft4Validator(self.schema)
        self.errors = None
开发者ID:vfulco,项目名称:schema-sugar,代码行数:26,代码来源:__init__.py

示例2: load_validator

def load_validator(name):
    """ Load the JSON Schema Draft 4 validator with the given name from the
    local schema directory. """
    with open(os.path.join(SCHEMA_PATH, name)) as fh:
        schema = json.load(fh)
    Draft4Validator.check_schema(schema)
    return Draft4Validator(schema, format_checker=checker)
开发者ID:COLABORATI,项目名称:babbage,代码行数:7,代码来源:validation.py

示例3: validate

 def validate(self):
     self.log.info("Checking schemas for validity")
     for application in self.applications.values():
         self.log.info("+ " + application.slug)
         for collection in application.collections:
             self.log.info('--- ' + collection.slug)
             Draft4Validator.check_schema(collection.schema)
开发者ID:JeffHeard,项目名称:sondra,代码行数:7,代码来源:__init__.py

示例4: __init__

    def __init__(self, schema=DEFAULT_LTM_SCHEMA):
        """Choose schema and initialize extended Draft4Validator.

        Raises:
            F5CcclSchemaError: Failed to read or validate the CCCL
            API schema file.
        """

        try:
            self.schema = read_yaml_or_json(schema)
        except json.JSONDecodeError as error:
            LOGGER.error("%s", error)
            raise cccl_exc.F5CcclSchemaError(
                'CCCL API schema could not be decoded.')
        except IOError as error:
            LOGGER.error("%s", error)
            raise cccl_exc.F5CcclSchemaError(
                'CCCL API schema could not be read.')

        try:
            Draft4Validator.check_schema(self.schema)
            self.validate_properties = Draft4Validator.VALIDATORS["properties"]
            validator_with_defaults = validators.extend(
                Draft4Validator,
                {"properties": self.__set_defaults})
            self.validator = validator_with_defaults(self.schema)
        except jsonschema.SchemaError as error:
            LOGGER.error("%s", error)
            raise cccl_exc.F5CcclSchemaError("Invalid API schema")
开发者ID:russokj,项目名称:f5-cccl,代码行数:29,代码来源:validation.py

示例5: test_select_all

 def test_select_all(self, testapi):
     """
     Select all link relations and check them for valid JSON schema.
     """
     for rel_id in testapi.get(url_for('v1.LinkRelationsView:index')).json.keys():
         resp = testapi.get(url_for('v1.LinkRelationsView:get',id=rel_id))
         Draft4Validator.check_schema(resp.json).should.be(None)
开发者ID:dwcaraway,项目名称:govly,代码行数:7,代码来源:test_rels.py

示例6: serialize

    def serialize(self):
        """Serialize the schema to a pure Python data structure.

        After serializing the schema once, it's not possible to mutate
        self._schema any more, since these changes would not be reflected in
        the serialized output.
        """
        # Order keys before serializing.
        # This is to get a stable sort order when dumping schemas, and a
        # convenient API at the same time (no need to pass in OrderedDicts
        # all the time). This keeps calling code more readable.
        self._schema = order_dict(self._schema, SCHEMA_KEYS_ORDER)
        if 'properties' in self._schema:
            for prop_name, prop_def in self._schema['properties'].items():
                self._schema['properties'][prop_name] = order_dict(
                    prop_def, PROPERTY_KEYS_ORDER)

        schema = deepcopy(self._schema)
        Draft4Validator.check_schema(schema)

        # Prevent access to self._schema after serialization in order to avoid
        # gotchas where mutations to self._schema don't take effect any more
        del self._schema

        return schema
开发者ID:4teamwork,项目名称:opengever.core,代码行数:25,代码来源:json_schema_helper.py

示例7: _validate

 def _validate(self):
     # Draft4Validator accepts empty JSON, but we don't want to accept it.
     if not self.json:
         raise ValueError('Schema is invalid.')
     try:
         Draft4Validator.check_schema(self.json)
     except (SchemaError, ValidationError):
         raise ValueError('Schema is invalid.')
开发者ID:FGtatsuro,项目名称:Caprice,代码行数:8,代码来源:models.py

示例8: test_schemas_are_valid

def test_schemas_are_valid():
    root_dir = os.path.join(
        'inspirehep', 'modules', 'records', 'jsonschemas', 'records')
    for schemas_dir, _, schemas in os.walk(root_dir):
        schemas_path = os.path.sep.join(schemas_dir.split(os.path.sep)[1:])
        for schema in schemas:
            schema_path = os.path.join(schemas_path, schema)
            Draft4Validator.check_schema(fetch_schema(schema_path))
开发者ID:kaplun,项目名称:inspire-next,代码行数:8,代码来源:test_records_jsonschemas.py

示例9: json_schema_validator

def json_schema_validator(value):
    """
    raises ValidationError if value is not a valid json schema
    """
    try:
        Draft4Validator.check_schema(value)
    except SchemaError as e:
        raise ValidationError(_('Schema is invalid: %(msg)s'),
                              params={"msg": str(e.message)})
开发者ID:zyphrus,项目名称:fetch-django,代码行数:9,代码来源:validators.py

示例10: test_schema_validity

def test_schema_validity():
    for name in ("schema_base.json",
                 "schema_data.json",
                 "schema_node.json",
                 "schema_prov_exe.json",
                 "schema_workflow.json"):
        with open(os.path.join(sch_pth, name), 'r') as f:
            schema = json.load(f)
            Draft4Validator.check_schema(schema)
开发者ID:openalea,项目名称:wlformat,代码行数:9,代码来源:test_schema_validity.py

示例11: test

def test():
    """Tests all included schemata against the Draft4Validator"""

    from jsonschema import Draft4Validator

    for schemaname, schemadata in schemastore.items():
        hfoslog("[SCHEMATA] Validating schema ", schemaname)
        Draft4Validator.check_schema(schemadata['schema'])
        if 'uuid' not in schemadata['schema']:
            hfoslog("[SCHEMATA] Schema without uuid encountered: ", schemaname, lvl=debug)
开发者ID:addy2342,项目名称:hfos,代码行数:10,代码来源:__init__.py

示例12: schema

 def schema(self, schema):
     """sets the stream's schema. An empty schema is "{}". The schemas allow you to set a specific data type. 
     Both python dicts and strings are accepted."""
     if isinstance(schema, basestring):
         strschema = schema
         schema = json.loads(schema)
     else:
         strschema = json.dumps(schema)
     Draft4Validator.check_schema(schema)
     self.set({"schema": strschema})
开发者ID:connectordb,项目名称:connectordb-python,代码行数:10,代码来源:_stream.py

示例13: test_schema_handler_with_default_uri_normalization

 def test_schema_handler_with_default_uri_normalization(self):
     response = self.fetch('/person/Gender/_schema')
     self.assertEqual(response.code, 200)
     schema = json.loads(response.body)
     self.assertEqual(schema['id'], u'http://semantica.globo.com/person/Gender')
     self.assertEqual(schema['$schema'], 'http://json-schema.org/draft-04/schema#')
     try:
         Draft4Validator.check_schema(schema)
     except SchemaError as ex:
         self.fail("Json-schema for class {0} is not valid. Failed for {1:s}".format('person:Gender', ex))
开发者ID:gustavoferreira,项目名称:brainiak_api,代码行数:10,代码来源:test_get_class.py

示例14: load_schema

def load_schema(schema):
    """Validates the given schema and returns an associated schema validator
    object that can check other objects' conformance to the schema.

    :param schema: The JSON schema object.
    :returns: The object loaded in from the JSON schema file.

    """
    Draft4Validator.check_schema(schema)
    return Draft4Validator(schema, format_checker=FormatChecker())
开发者ID:jon-armstrong,项目名称:provoke,代码行数:10,代码来源:util.py

示例15: validateSchemasInFolder

def validateSchemasInFolder(folder):
    path = os.path.abspath(folder)
    files = [ f for f in listdir(path) if isfile(join(path,f)) ]

    for schemaFile in files:
        if (schemaFile.endswith('.json')):
            print("Validating schema ", schemaFile, "...")
            schema = json.load(open(join(path,schemaFile)))
            Draft4Validator.check_schema(schema)
            print("done.")
开发者ID:proccaserra,项目名称:isa-api,代码行数:10,代码来源:validate_schemas.py


注:本文中的jsonschema.Draft4Validator类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。