本文整理汇总了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
示例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)
示例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)
示例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")
示例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)
示例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
示例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.')
示例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))
示例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)})
示例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)
示例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)
示例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})
示例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))
示例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())
示例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.")