本文整理汇总了Python中jsonschema.RefResolver方法的典型用法代码示例。如果您正苦于以下问题:Python jsonschema.RefResolver方法的具体用法?Python jsonschema.RefResolver怎么用?Python jsonschema.RefResolver使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类jsonschema
的用法示例。
在下文中一共展示了jsonschema.RefResolver方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: get_validator
# 需要导入模块: import jsonschema [as 别名]
# 或者: from jsonschema import RefResolver [as 别名]
def get_validator(filename, base_uri=''):
"""Load schema from JSON file;
Check whether it's a valid schema;
Return a Draft4Validator object.
Optionally specify a base URI for relative path
resolution of JSON pointers (This is especially useful
for local resolution via base_uri of form file://{some_path}/)
"""
schema = get_json_from_file(filename)
try:
# Check schema via class method call. Works, despite IDE complaining
Draft4Validator.check_schema(schema)
print("Schema %s is valid JSON" % filename)
except SchemaError:
raise
if base_uri:
resolver = RefResolver(base_uri=base_uri,
referrer=filename)
else:
resolver = None
return Draft4Validator(schema=schema,
resolver=resolver)
示例2: testJsonSchema
# 需要导入模块: import jsonschema [as 别名]
# 或者: from jsonschema import RefResolver [as 别名]
def testJsonSchema(schema_file, test_file):
schema = loadSchema(schema_file)
data = loadJson(test_file)
print 'Loaded test validation JSON value from %s:' % test_file
dir = os.path.dirname(os.path.realpath(__file__))
resolver = jsonschema.RefResolver(referrer=schema, base_uri='file://' + dir + '/')
try:
jsonschema.validate(data, schema, resolver=resolver)
except jsonschema.exceptions.ValidationError as e:
print e
print 'FAILED VALIDATION for %s' % test_file
pprint(data)
return 1
print 'Validated.'
return 0
示例3: is_valid_response
# 需要导入模块: import jsonschema [as 别名]
# 或者: from jsonschema import RefResolver [as 别名]
def is_valid_response(action, resp={}):
assert action.name in actions.keys()
schema_for = {
"IndexState": "State",
"Index": "IndexReport",
"GetIndexReport": "IndexReport",
"GetVulnerabilityReport": "VulnerabilityReport",
}
filename = os.path.join(os.path.dirname(os.path.abspath(__file__)), "clair-v4.openapi.json")
with open(filename) as openapi_file:
openapi = json.load(openapi_file)
resolver = RefResolver(base_uri="", referrer=openapi)
schema = openapi["components"]["schemas"][schema_for[action.name]]
try:
validate(resp, schema, resolver=resolver)
return True
except Exception:
logger.exception("Security scanner response failed OpenAPI validation")
return False
示例4: _get_schema
# 需要导入模块: import jsonschema [as 别名]
# 或者: from jsonschema import RefResolver [as 别名]
def _get_schema(file_type):
'''Get a schema that can validate BSE JSON files or dictionaries
The schema_type represents the type of BSE JSON file to be validated,
and can be 'component', 'element', 'table', 'metadata', or 'references'.
Returns the schema and the reference resolver
'''
schema_file = "{}-schema.json".format(file_type)
file_path = os.path.join(_default_schema_dir, schema_file)
schema = fileio.read_schema(file_path)
# Set up the resolver for links
base_uri = 'file://{}/'.format(_default_schema_dir)
resolver = jsonschema.RefResolver(base_uri=base_uri, referrer=schema)
return schema, resolver
示例5: validate
# 需要导入模块: import jsonschema [as 别名]
# 或者: from jsonschema import RefResolver [as 别名]
def validate(spec, schema_name, version=None):
schema = load_schema(schema_name, version=version)
try:
resolver = jsonschema.RefResolver(
base_uri='file://{0:s}'.format(
pkg_resources.resource_filename(__name__, 'schemas/')
),
referrer=schema_name,
store=SCHEMA_CACHE,
)
validator = jsonschema.Draft6Validator(
schema, resolver=resolver, format_checker=None
)
return validator.validate(spec)
except jsonschema.ValidationError as err:
raise InvalidSpecification(err)
示例6: setup_class
# 需要导入模块: import jsonschema [as 别名]
# 或者: from jsonschema import RefResolver [as 别名]
def setup_class(cls):
"""Set the test up."""
cls.schema = json.load(open(AGENT_CONFIGURATION_SCHEMA))
cls.resolver = jsonschema.RefResolver(
"file://{}/".format(Path(CONFIGURATION_SCHEMA_DIR).absolute()), cls.schema
)
cls.validator = Draft4Validator(cls.schema, resolver=cls.resolver)
cls.cwd = os.getcwd()
cls.t = tempfile.mkdtemp()
# copy the 'dummy_aea' directory in the parent of the agent folder.
shutil.copytree(Path(CUR_PATH, "data", "dummy_aea"), Path(cls.t, "dummy_aea"))
cls.runner = CliRunner()
os.chdir(Path(cls.t, "dummy_aea"))
with mock.patch(
"aea.cli.list.format_items", return_value=FORMAT_ITEMS_SAMPLE_OUTPUT
):
cls.result = cls.runner.invoke(
cli, [*CLI_LOG_OPTION, "list", "protocols"], standalone_mode=False
)
示例7: setup_class
# 需要导入模块: import jsonschema [as 别名]
# 或者: from jsonschema import RefResolver [as 别名]
def setup_class(cls):
"""Set the test up."""
cls.schema = json.load(open(AGENT_CONFIGURATION_SCHEMA))
cls.resolver = jsonschema.RefResolver(
make_jsonschema_base_uri(Path(CONFIGURATION_SCHEMA_DIR).absolute()),
cls.schema,
)
cls.validator = Draft4Validator(cls.schema, resolver=cls.resolver)
cls.runner = CliRunner()
cls.agent_name = "myagent"
cls.cwd = os.getcwd()
cls.t = tempfile.mkdtemp()
os.chdir(cls.t)
result = cls.runner.invoke(
cli, [*CLI_LOG_OPTION, "init", "--local", "--author", AUTHOR]
)
assert result.exit_code == 0
cls.result = cls.runner.invoke(
cli,
[*CLI_LOG_OPTION, "create", "--local", cls.agent_name],
standalone_mode=False,
)
cls.agent_config = cls._load_config_file(cls.agent_name)
示例8: setup_class
# 需要导入模块: import jsonschema [as 别名]
# 或者: from jsonschema import RefResolver [as 别名]
def setup_class(cls):
"""Set the test up."""
cls.schema = json.load(open(AGENT_CONFIGURATION_SCHEMA))
cls.resolver = jsonschema.RefResolver(
make_jsonschema_base_uri(Path(CONFIGURATION_SCHEMA_DIR)), cls.schema
)
cls.validator = Draft4Validator(cls.schema, resolver=cls.resolver)
cls.cwd = os.getcwd()
cls.t = tempfile.mkdtemp()
# copy the 'dummy_aea' directory in the parent of the agent folder.
shutil.copytree(Path(CUR_PATH, "data", "dummy_aea"), Path(cls.t, "dummy_aea"))
cls.runner = CliRunner()
os.chdir(Path(cls.t, "dummy_aea"))
cls.result = cls.runner.invoke(
cli, [*CLI_LOG_OPTION, "freeze"], standalone_mode=False
)
示例9: __init__
# 需要导入模块: import jsonschema [as 别名]
# 或者: from jsonschema import RefResolver [as 别名]
def __init__(self, versions, path, skip_unknown=False, min_date='2016.09.01', future_hours=24):
"""
Класс для валидации документов от ККТ по json-схеме.
:param versions: поддерживаемые версии протокола, например ['1.0', '1.05'].
:param path: путь до директории, которая содержит все директории со схемами, разбитым по версиям,
например, схемы для протокола 1.0 должны лежать в <path>/1.0/
:param skip_unknown: если номер версии отличается от поддерживаемых пропускать валидацию
"""
self._validators = {}
self._skip_unknown = skip_unknown
schema_dir = os.path.expanduser(path)
schema_dir = os.path.abspath(schema_dir)
self.min_date = datetime.datetime.strptime(min_date, '%Y.%m.%d') if min_date else None
self.future_hours = future_hours
for version in versions:
full_path = os.path.join(schema_dir, version, 'document.schema.json')
with open(full_path, encoding='utf-8') as fh:
schema = json.loads(fh.read())
resolver = jsonschema.RefResolver('file://' + full_path, None)
validator = Draft4Validator(schema=schema, resolver=resolver)
validator.check_schema(schema) # проверяем, что сама схема - валидная
self._validators[version] = validator
示例10: _create_validator
# 需要导入模块: import jsonschema [as 别名]
# 或者: from jsonschema import RefResolver [as 别名]
def _create_validator(schema: Dict) -> Draft4Validator:
"""resolve $ref links in a loaded json schema and return a validator
Parameters
----------
schema : Dict
loaded json schema
Returns
-------
Draft4Validator :
json-schema validator specific to the supplied schema, with references resolved
"""
# Note: we are using 5.0.0 here as the first known file. It does *not* need to
# be upgraded with each version bump since only the dirname is used.
experiment_schema_path = Path(resource_filename(
package_name, "spacetx_format/schema/experiment_5.0.0.json"))
package_root_path = experiment_schema_path.parent.parent
base_uri = f"{package_root_path.as_uri()}/"
resolver = RefResolver(base_uri, schema)
return Draft4Validator(schema, resolver=resolver)
示例11: validate_JSON
# 需要导入模块: import jsonschema [as 别名]
# 或者: from jsonschema import RefResolver [as 别名]
def validate_JSON(data,combined_schema):
for keys in combined_schema['properties']:
if "$ref" in (combined_schema['properties'])[keys]:
refUrl= ((combined_schema['properties'])[keys])['$ref']
references_file, section = refUrl.split('#')
if not os.path.isfile(references_file):
print "References file does not exists"
sys.exit()
schema_dir = os.path.dirname(os.path.realpath(references_file))
resolver = RefResolver("file://{}/".format(schema_dir), None)
try:
validate(data,combined_schema,format_checker=FormatChecker(), resolver=resolver)
print "JSON is valid with the schema"
return True
except exceptions.ValidationError as error:
print(error.message)
return False
#Merging schemas and putting key translations
示例12: make_validator
# 需要导入模块: import jsonschema [as 别名]
# 或者: from jsonschema import RefResolver [as 别名]
def make_validator(schema, base_uri=None):
if not base_uri:
base_uri = Draft7Validator.ID_OF(schema)
def get_from_local(uri): # pylint: disable=unused-argument
meta_schema = Path(os.path.dirname(os.path.realpath(__file__))).joinpath(
"data/schema/meta-schema.json"
)
return json.load(meta_schema.open())
resolver = RefResolver(
base_uri=base_uri,
referrer=schema,
handlers={"http": get_from_local, "https": get_from_local},
)
return Draft7Validator(schema, resolver=resolver)
示例13: test_non_default_resolver_validator
# 需要导入模块: import jsonschema [as 别名]
# 或者: from jsonschema import RefResolver [as 别名]
def test_non_default_resolver_validator(markdown_examples):
ms = URIDict()
draft3 = load_schema("draft3")
draft4 = load_schema("draft4")
ms[draft3["id"]] = draft3
ms[draft4["id"]] = draft4
resolver_with_store = RefResolver(draft3["id"], draft3, ms)
# 'Other' schema should be valid with draft3
builder = pjo.ObjectBuilder(
markdown_examples["Other"],
resolver=resolver_with_store,
validatorClass=Draft3Validator,
resolved=markdown_examples,
)
klasses = builder.build_classes()
a = klasses.Other(MyAddress="where I live")
assert a.MyAddress == "where I live"
示例14: resolve_schema_references
# 需要导入模块: import jsonschema [as 别名]
# 或者: from jsonschema import RefResolver [as 别名]
def resolve_schema_references(schema, refs=None):
'''Resolves and replaces json-schema $refs with the appropriate dict.
Recursively walks the given schema dict, converting every instance
of $ref in a 'properties' structure with a resolved dict.
This modifies the input schema and also returns it.
Arguments:
schema:
the schema dict
refs:
a dict of <string, dict> which forms a store of referenced schemata
Returns:
schema
'''
refs = refs or {}
return _resolve_schema_references(schema, RefResolver("", schema, store=refs))
示例15: validate
# 需要导入模块: import jsonschema [as 别名]
# 或者: from jsonschema import RefResolver [as 别名]
def validate(self, data=None):
if not data:
data = self.config_dict
schema_dir = "/usr/share/contrailctl/schema/"
schema_path="{}/{}.json".format(schema_dir, self.component)
resolver = RefResolver("file://{}/".format(schema_dir), None)
try:
schema=open(schema_path,'r').read()
except IOError as error:
print("Schema file is missing - {}".format(schema_path))
return True
try:
validate(data, json.loads(schema), format_checker=FormatChecker(), resolver=resolver)
return True
except exceptions.ValidationError as error:
print(error.message)
return False