本文整理汇总了Python中jsonschema.FormatChecker方法的典型用法代码示例。如果您正苦于以下问题:Python jsonschema.FormatChecker方法的具体用法?Python jsonschema.FormatChecker怎么用?Python jsonschema.FormatChecker使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类jsonschema
的用法示例。
在下文中一共展示了jsonschema.FormatChecker方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: validate
# 需要导入模块: import jsonschema [as 别名]
# 或者: from jsonschema import FormatChecker [as 别名]
def validate(self, json_object):
results = ValidationResults()
if "$schemaRef" not in json_object:
results.add(ValidationSeverity.FATAL, JsonValidationException("No $schemaRef found, unable to validate."))
return results
schemaRef = json_object["$schemaRef"]
if schemaRef not in self.schemas.keys():
# We don't want to go out to the Internet and retrieve unknown schemas.
results.add(ValidationSeverity.FATAL, JsonValidationException("Schema " + schemaRef + " is unknown, unable to validate."))
return results
schema = self.schemas[schemaRef]
try:
jsValidate(json_object, schema, format_checker=FormatChecker())
except ValidationError as e:
results.add(ValidationSeverity.ERROR, e)
return results
示例2: add
# 需要导入模块: import jsonschema [as 别名]
# 或者: from jsonschema import FormatChecker [as 别名]
def add(self, message):
if isinstance(message, singer.RecordMessage):
stream = self.ensure_stream(message.stream)
if stream.latest_schema:
validator_fn = extend_with_default(Draft4Validator)
validator = validator_fn(
stream.latest_schema, format_checker=FormatChecker())
validator.validate(copy.deepcopy(message.record))
else:
print('I saw a record for stream {} before the schema'.format(
message.stream))
exit(1)
stream.num_records += 1
elif isinstance(message, singer.SchemaMessage):
stream = self.ensure_stream(message.stream)
stream.num_schemas += 1
stream.latest_schema = message.schema
elif isinstance(message, singer.StateMessage):
self.latest_state = message.value
self.num_states += 1
示例3: validate_host_mapping
# 需要导入模块: import jsonschema [as 别名]
# 或者: from jsonschema import FormatChecker [as 别名]
def validate_host_mapping(host_mapping):
"""
Validate a provided host mapping.
:param dict host_mapping: The parsed JSON host mapping from the
environment variable ``FLOCKER_ACCEPTANCE_HOSTNAME_TO_PUBLIC_ADDRESS``.
:raises: jsonschema.ValidationError if the configuration is invalid.
"""
schema = {
"$schema": "http://json-schema.org/draft-04/schema#",
"type": "object",
"additionalProperties": "true",
}
v = Draft4Validator(schema, format_checker=FormatChecker())
v.validate(host_mapping)
示例4: validate_json
# 需要导入模块: import jsonschema [as 别名]
# 或者: from jsonschema import FormatChecker [as 别名]
def validate_json(value, schema):
v = Draft4Validator(schema, format_checker=FormatChecker())
errors = sorted(v.iter_errors(value), key=lambda e: e.path)
message_dict = {}
for e in errors:
if e.validator == 'anyOf':
fields = [
f.message.split(' ')[0].replace('\'', '') for f in e.context
]
for f in fields:
message_dict[f] = _("Please provide either {}").format(
_(" or ").join(fields))
elif e.validator == 'required':
field = e.message.split(' ')[0].replace('\'', '')
message_dict[field] = _("This field is required.")
else:
field = '.'.join([str(el) for el in e.path])
message_dict[field] = e.message
if message_dict:
raise JsonValidationError(message_dict)
示例5: validate_json
# 需要导入模块: import jsonschema [as 别名]
# 或者: from jsonschema import FormatChecker [as 别名]
def validate_json(json_obj):
with open(SCHEMA_PATH) as s:
json_schema = json.load(s)
# first validate schema file
v = jsonschema.Draft4Validator(json_schema)
# now validate json file
try:
jsonschema.validate(json_obj, json_schema, format_checker=jsonschema.FormatChecker())
logger.info('The file is valid. Validation passed.')
return True
except jsonschema.exceptions.ValidationError:
errors = [e for e in v.iter_errors((json_obj))]
logger.info(f"The file is not valid. Total errors: {len(errors)}")
for i, error in enumerate(errors, 1):
logger.error(f"{i} Validation error in {'.'.join(str(v) for v in error.path)}: {error.message}")
logger.info('Validation failed.')
return False
示例6: validate_JSON
# 需要导入模块: import jsonschema [as 别名]
# 或者: from jsonschema import FormatChecker [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
示例7: full_validate
# 需要导入模块: import jsonschema [as 别名]
# 或者: from jsonschema import FormatChecker [as 别名]
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)
示例8: _validate_create_body
# 需要导入模块: import jsonschema [as 别名]
# 或者: from jsonschema import FormatChecker [as 别名]
def _validate_create_body(self, body):
schedule = body.get("schedule")
if schedule is None:
raise exception.InvalidInput(
"schedule is required")
schedule = self._validate_schedule(schedule)
schemas.validate_value(
body, schemas.SCHEDULE_API_BODY_SCHEMA,
format_checker=jsonschema.FormatChecker())
enabled = body.get("enabled", True)
exp = body.get("expiration_date", None)
if exp is not None:
exp = self._validate_expiration_date(exp)
shutdown = body.get("shutdown_instance", False)
return (schedule, enabled, exp, shutdown)
示例9: _validate_update_body
# 需要导入模块: import jsonschema [as 别名]
# 或者: from jsonschema import FormatChecker [as 别名]
def _validate_update_body(self, update_body):
body = {}
schedule = update_body.get("schedule")
if schedule is not None:
schedule = self._validate_schedule(schedule)
body["schedule"] = schedule
enabled = update_body.get("enabled")
if enabled is not None:
body["enabled"] = enabled
shutdown = update_body.get("shutdown_instance")
if shutdown is not None:
body["shutdown_instance"] = shutdown
schemas.validate_value(
body, schemas.SCHEDULE_API_BODY_SCHEMA,
format_checker=jsonschema.FormatChecker())
exp = None
if "expiration_date" in update_body:
exp = self._validate_expiration_date(
update_body.get("expiration_date"))
body["expiration_date"] = exp
return body
示例10: validate
# 需要导入模块: import jsonschema [as 别名]
# 或者: from jsonschema import FormatChecker [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
示例11: require_schema
# 需要导入模块: import jsonschema [as 别名]
# 或者: from jsonschema import FormatChecker [as 别名]
def require_schema(schema):
"""This decorator verifies that request JSON matches given JSONSchema.
http://json-schema.org
"""
validator = jsonschema.Draft4Validator(
schema,
format_checker=jsonschema.FormatChecker()
)
def outer_decorator(func):
@functools.wraps(func)
def inner_decorator(self, *args, **kwargs):
errors = validator.iter_errors(self.request_json)
errors = [err.message for err in errors]
if errors:
LOG.warning("Cannot validate request: %s", errors)
raise exceptions.InvalidJSONError(errors)
return func(self, *args, **kwargs)
return inner_decorator
return outer_decorator
示例12: __init__
# 需要导入模块: import jsonschema [as 别名]
# 或者: from jsonschema import FormatChecker [as 别名]
def __init__(self, schema, is_body=True):
self.is_body = is_body
validators = {
'minimum': self._validate_minimum,
'maximum': self._validate_maximum
}
validator_cls = jsonschema.validators.extend(self.validator_org,
validators)
fc = jsonschema.FormatChecker()
self.validator = validator_cls(schema, format_checker=fc)
示例13: is_valid_json
# 需要导入模块: import jsonschema [as 别名]
# 或者: from jsonschema import FormatChecker [as 别名]
def is_valid_json(data, schema):
checker = FormatChecker()
# add the "interval" format
checker.checks("interval")(parse_iso8601_interval)
validator = Draft4Validator(schema, format_checker=checker)
errors = []
for error in validator.iter_errors(data):
errors.append(error.message)
return errors
示例14: _assert_schema
# 需要导入模块: import jsonschema [as 别名]
# 或者: from jsonschema import FormatChecker [as 别名]
def _assert_schema(self, schema, reality):
try:
validate(reality, schema, format_checker=FormatChecker())
except SchemaError as e:
raise RuntimeError(e)
except ValidationError as e:
raise AssertionError(e)
示例15: validate_cluster_configuration
# 需要导入模块: import jsonschema [as 别名]
# 或者: from jsonschema import FormatChecker [as 别名]
def validate_cluster_configuration(cluster_config):
"""
Validate a provided cluster configuration.
:param dict cluster_config: The cluster configuration.
:raises: jsonschema.ValidationError if the configuration is invalid.
"""
schema = {
"$schema": "http://json-schema.org/draft-04/schema#",
"type": "object",
"required": ["control_node", "agent_nodes"],
"properties": {
"control_node": {
"type": "string",
},
"agent_nodes": {
"type": "array",
"items": {
"type": "object",
"required": ["public", "private"],
"properties": {
"public": {
"type": "string"
},
"private": {
"type": "string"
},
},
},
},
},
"additionalProperties": "true",
}
v = Draft4Validator(schema, format_checker=FormatChecker())
v.validate(cluster_config)