本文整理汇总了Python中fastjsonschema.compile方法的典型用法代码示例。如果您正苦于以下问题:Python fastjsonschema.compile方法的具体用法?Python fastjsonschema.compile怎么用?Python fastjsonschema.compile使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类fastjsonschema
的用法示例。
在下文中一共展示了fastjsonschema.compile方法的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: fast_validate
# 需要导入模块: import fastjsonschema [as 别名]
# 或者: from fastjsonschema import compile [as 别名]
def fast_validate(
schema: RawSchema, raw_items: RawItems, keys: pd.Index
) -> Dict[str, set]:
"""Verify items one by one. It stops after the first error in an item in most cases.
Faster than jsonschema validation
Args:
schema: a JSON schema
raw_items: a raw data to validate one by one
keys: keys corresponding to raw_items index
Returns:
A dictionary of errors with message and item keys
"""
errors: DefaultDict = defaultdict(set)
validate = fastjsonschema.compile(schema)
for i, raw_item in enumerate(tqdm(raw_items, desc="Fast Schema Validation")):
raw_item.pop("_type", None)
raw_item.pop("_key", None)
try:
validate(raw_item)
except fastjsonschema.JsonSchemaException as error:
errors[str(error)].add(keys[i])
return dict(errors)
示例2: validate
# 需要导入模块: import fastjsonschema [as 别名]
# 或者: from fastjsonschema import compile [as 别名]
def validate(definition, data, handlers={}, formats={}):
"""
Validation function for lazy programmers or for use cases, when you need
to call validation only once, so you do not have to compile it first.
Use it only when you do not care about performance (even thought it will
be still faster than alternative implementations).
.. code-block:: python
import fastjsonschema
fastjsonschema.validate({'type': 'string'}, 'hello')
# same as: compile({'type': 'string'})('hello')
Preferred is to use :any:`compile` function.
"""
return compile(definition, handlers, formats)(data)
# pylint: disable=redefined-builtin,dangerous-default-value,exec-used
示例3: asserter
# 需要导入模块: import fastjsonschema [as 别名]
# 或者: from fastjsonschema import compile [as 别名]
def asserter():
def f(definition, value, expected, formats={}):
# When test fails, it will show up code.
code_generator = CodeGeneratorDraft07(definition, formats=formats)
print(code_generator.func_code)
pprint(code_generator.global_state)
# By default old tests are written for draft-04.
definition.setdefault('$schema', 'http://json-schema.org/draft-04/schema')
validator = compile(definition, formats=formats)
if isinstance(expected, JsonSchemaException):
with pytest.raises(JsonSchemaException) as exc:
validator(value)
assert exc.value.message == expected.message
assert exc.value.value == (value if expected.value == '{data}' else expected.value)
assert exc.value.name == expected.name
assert exc.value.definition == (definition if expected.definition == '{definition}' else expected.definition)
assert exc.value.rule == expected.rule
else:
assert validator(value) == expected
return f
示例4: _validate
# 需要导入模块: import fastjsonschema [as 别名]
# 或者: from fastjsonschema import compile [as 别名]
def _validate(cls, data: JsonDict, validate_enums: bool = True):
try:
if fast_validation:
# TODO: Support validating with other schema types
schema_validator = cls.__compiled_schema.get(SchemaOptions(DEFAULT_SCHEMA_TYPE, validate_enums))
if schema_validator is None:
schema_validator = fastjsonschema.compile(cls.json_schema(validate_enums=validate_enums))
cls.__compiled_schema[SchemaOptions(DEFAULT_SCHEMA_TYPE, validate_enums)] = schema_validator
schema_validator(data)
else:
validate_func(data, cls.json_schema(validate_enums=validate_enums))
except JsonSchemaValidationError as e:
raise ValidationError(str(e)) from e
示例5: _validate
# 需要导入模块: import fastjsonschema [as 别名]
# 或者: from fastjsonschema import compile [as 别名]
def _validate(req_schema: Dict = None, resp_schema: Dict = None):
def decorator(func):
@wraps(func)
def wrapper(self, req, resp, *args, **kwargs):
if req_schema is not None:
try:
schema = fastjsonschema.compile(req_schema)
schema(req.media)
except fastjsonschema.JsonSchemaException as e:
msg = "Request data failed validation: {}".format(e.message)
raise HTTPError(falcon.HTTP_BAD_REQUEST, msg)
result = func(self, req, resp, *args, **kwargs)
if resp_schema is not None:
try:
schema = fastjsonschema.compile(resp_schema)
schema(resp.media)
except fastjsonschema.JsonSchemaException:
raise HTTPError(
falcon.HTTP_INTERNAL_SERVER_ERROR,
"Response data failed validation",
)
# Do not return 'e.message' in the response to
# prevent info about possible internal response
# formatting bugs from leaking out to users.
return result
return wrapper
return decorator
示例6: getJsValidator
# 需要导入模块: import fastjsonschema [as 别名]
# 或者: from fastjsonschema import compile [as 别名]
def getJsValidator(schema):
'''
Get a fastjsonschema callable.
Args:
schema (dict): A JSON Schema object.
Returns:
callable: A callable function that can be used to validate data against the json schema.
'''
if schema.get('$schema') is None:
schema['$schema'] = 'http://json-schema.org/draft-07/schema#'
# It is faster to hash and cache the functions here than it is to
# generate new functions each time we have the same schema.
key = s_hashitem.hashitem(schema)
func = _JsValidators.get(key)
if func:
return func
func = fastjsonschema.compile(schema)
def wrap(*args, **kwargs):
try:
return func(*args, **kwargs)
except JsonSchemaException as e:
raise s_exc.SchemaViolation(mesg=e.message, name=e.name)
_JsValidators[key] = wrap
return wrap
示例7: template_test
# 需要导入模块: import fastjsonschema [as 别名]
# 或者: from fastjsonschema import compile [as 别名]
def template_test(schema_version, schema, data, is_valid):
"""
Test function to be used (imported) in final test file to run the tests
which are generated by `pytest_generate_tests` hook.
"""
# For debug purposes. When test fails, it will print stdout.
resolver = RefResolver.from_schema(schema, handlers={'http': remotes_handler})
debug_generator = _get_code_generator_class(schema_version)(schema, resolver=resolver)
print(debug_generator.global_state_code)
print(debug_generator.func_code)
# JSON schema test suits do not contain schema version.
# Our library needs to know that or it would use always the latest implementation.
if isinstance(schema, dict):
schema.setdefault('$schema', schema_version)
validate = compile(schema, handlers={'http': remotes_handler})
try:
result = validate(data)
print('Validate result:', result)
except JsonSchemaException:
if is_valid:
raise
else:
if not is_valid:
pytest.fail('Test should not pass')
示例8: test_invalid_properties
# 需要导入模块: import fastjsonschema [as 别名]
# 或者: from fastjsonschema import compile [as 别名]
def test_invalid_properties(asserter):
with pytest.raises(JsonSchemaDefinitionException):
fastjsonschema.compile({
'properties': {
'item': ['wrong'],
},
})
示例9: fast_not_compiled
# 需要导入模块: import fastjsonschema [as 别名]
# 或者: from fastjsonschema import compile [as 别名]
def fast_not_compiled(value, json_schema):
fastjsonschema.compile(json_schema)(value)
示例10: __init__
# 需要导入模块: import fastjsonschema [as 别名]
# 或者: from fastjsonschema import compile [as 别名]
def __init__(
self,
app: web.Application,
*,
validate: bool,
spec: Dict,
request_key: str,
swagger_ui_settings: Optional[SwaggerUiSettings],
redoc_ui_settings: Optional[ReDocUiSettings],
rapidoc_ui_settings: Optional[RapiDocUiSettings],
) -> None:
self._app = app
self.validate = validate
self.spec = spec
self.request_key = request_key
self.handlers: DefaultDict[
str, Dict[str, Callable[[web.Request], Awaitable[Tuple[Any, bool]]]]
] = defaultdict(dict)
uis = (rapidoc_ui_settings, redoc_ui_settings, swagger_ui_settings)
paths: Set[str] = set()
for ui in uis:
if ui is None:
continue
if ui.path in paths:
raise Exception("cannot bind two UIs on the same path")
paths.add(ui.path)
base_path = pathlib.Path(__file__).parent
with open(base_path / "schema/schema.json") as f:
schema = json.load(f)
self.spec_validate = fastjsonschema.compile(
schema, formats={"uri-reference": r"^\w+:(\/?\/?)[^\s]+\Z|^#(\/\w+)+"}
)
self.spec_validate(self.spec)
for ui in uis:
if ui is not None:
self._register_ui(ui)
STRING_FORMATS.set({})
if self.validate:
self.register_media_type_handler("application/json", application_json)
self.register_media_type_handler(
"application/x-www-form-urlencoded", x_www_form_urlencoded
)
self.register_string_format_validator("byte", sf_byte_validator)
self.register_string_format_validator("date-time", sf_date_time_validator)
self.register_string_format_validator("date", sf_date_validator)
self.register_string_format_validator("email", sf_email_validator)
self.register_string_format_validator("hostname", sf_hostname_validator)
self.register_string_format_validator("ipv4", sf_ipv4_validator)
self.register_string_format_validator("ipv6", sf_ipv6_validator)
self.register_string_format_validator("uuid", sf_uuid_validator)
super().__init__()