本文整理汇总了Python中jsonschema.Draft4Validator.check_schema方法的典型用法代码示例。如果您正苦于以下问题:Python Draft4Validator.check_schema方法的具体用法?Python Draft4Validator.check_schema怎么用?Python Draft4Validator.check_schema使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类jsonschema.Draft4Validator
的用法示例。
在下文中一共展示了Draft4Validator.check_schema方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __init__
# 需要导入模块: from jsonschema import Draft4Validator [as 别名]
# 或者: from jsonschema.Draft4Validator import check_schema [as 别名]
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
示例2: load_validator
# 需要导入模块: from jsonschema import Draft4Validator [as 别名]
# 或者: from jsonschema.Draft4Validator import check_schema [as 别名]
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)
示例3: validate
# 需要导入模块: from jsonschema import Draft4Validator [as 别名]
# 或者: from jsonschema.Draft4Validator import check_schema [as 别名]
def validate(data, schema=None):
if schema is None:
schema = generate()
Validator.check_schema(schema)
validator = Validator(schema)
errors = list(validator.iter_errors(data))
if not errors:
counter = Counter([p['name'] for p in data.get('policies')])
dupes = []
for k, v in counter.items():
if v > 1:
dupes.append(k)
if dupes:
return [ValueError(
"Only one policy with a given name allowed, duplicates: %s" % (
", ".join(dupes)))]
return []
try:
resp = specific_error(errors[0])
name = isinstance(errors[0].instance, dict) and errors[0].instance.get('name', 'unknown') or 'unknown'
return [resp, name]
except Exception:
logging.exception(
"specific_error failed, traceback, followed by fallback")
return filter(None, [
errors[0],
best_match(validator.iter_errors(data)),
])
示例4: validate
# 需要导入模块: from jsonschema import Draft4Validator [as 别名]
# 或者: from jsonschema.Draft4Validator import check_schema [as 别名]
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)
示例5: __init__
# 需要导入模块: from jsonschema import Draft4Validator [as 别名]
# 或者: from jsonschema.Draft4Validator import check_schema [as 别名]
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")
示例6: validate
# 需要导入模块: from jsonschema import Draft4Validator [as 别名]
# 或者: from jsonschema.Draft4Validator import check_schema [as 别名]
def validate(data, schema=None):
if schema is None:
schema = generate()
Validator.check_schema(schema)
validator = Validator(schema)
errors = list(validator.iter_errors(data))
if not errors:
return check_unique(data) or []
try:
resp = policy_error_scope(specific_error(errors[0]), data)
name = isinstance(
errors[0].instance,
dict) and errors[0].instance.get(
'name',
'unknown') or 'unknown'
return [resp, name]
except Exception:
logging.exception(
"specific_error failed, traceback, followed by fallback")
return list(filter(None, [
errors[0],
best_match(validator.iter_errors(data)),
]))
示例7: test_select_all
# 需要导入模块: from jsonschema import Draft4Validator [as 别名]
# 或者: from jsonschema.Draft4Validator import check_schema [as 别名]
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)
示例8: serialize
# 需要导入模块: from jsonschema import Draft4Validator [as 别名]
# 或者: from jsonschema.Draft4Validator import check_schema [as 别名]
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
示例9: _validate
# 需要导入模块: from jsonschema import Draft4Validator [as 别名]
# 或者: from jsonschema.Draft4Validator import check_schema [as 别名]
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.')
示例10: test_schemas_are_valid
# 需要导入模块: from jsonschema import Draft4Validator [as 别名]
# 或者: from jsonschema.Draft4Validator import check_schema [as 别名]
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))
示例11: json_schema_validator
# 需要导入模块: from jsonschema import Draft4Validator [as 别名]
# 或者: from jsonschema.Draft4Validator import check_schema [as 别名]
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)})
示例12: test_schema_validity
# 需要导入模块: from jsonschema import Draft4Validator [as 别名]
# 或者: from jsonschema.Draft4Validator import check_schema [as 别名]
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)
示例13: validate
# 需要导入模块: from jsonschema import Draft4Validator [as 别名]
# 或者: from jsonschema.Draft4Validator import check_schema [as 别名]
def validate(schema_filename, data):
with open(schema_filename) as f:
schema = json.load(f) # cteme JSON Schema primo ze souboru
Validator.check_schema(schema) # zkontroluje schema nebo vyhodi vyjimku
base_uri = 'file://' + os.path.dirname(schema_filename) + '/'
resolver = RefResolver(base_uri, schema)
validator = Validator(schema, resolver=resolver)
return validator.iter_errors(data) # vraci chyby jednu po druhe
示例14: test
# 需要导入模块: from jsonschema import Draft4Validator [as 别名]
# 或者: from jsonschema.Draft4Validator import check_schema [as 别名]
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)
示例15: schema
# 需要导入模块: from jsonschema import Draft4Validator [as 别名]
# 或者: from jsonschema.Draft4Validator import check_schema [as 别名]
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})