本文整理汇总了Python中schema.Schema.validate方法的典型用法代码示例。如果您正苦于以下问题:Python Schema.validate方法的具体用法?Python Schema.validate怎么用?Python Schema.validate使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类schema.Schema
的用法示例。
在下文中一共展示了Schema.validate方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: is_valid
# 需要导入模块: from schema import Schema [as 别名]
# 或者: from schema.Schema import validate [as 别名]
def is_valid(self):
"""Checks if the input dictionary contains all valid types
Checks the __dict__ attribute and ensure it follows the correct
schema
Args:
None
Returns:
A Boolean if dictionary follows schema
"""
schema = Schema({
'region': unicode,
'subnet': unicode,
'purchase_type': And(unicode, lambda x: x in ["on_demand", "spot"]),
'image': unicode,
'price': unicode,
'num_instances': int,
'key_name': unicode,
'security_group_ids': list,
'instance_type': unicode,
'tag_name': unicode,
'vol_size': int,
'bdm': dict})
try:
schema.validate(self.__dict__)
return True
except Exception as exc:
print exc
print "Invalid instance template"
return False
示例2: _fit_first
# 需要导入模块: from schema import Schema [as 别名]
# 或者: from schema.Schema import validate [as 别名]
def _fit_first(self, first):
# Check for a tuples of numbers, strings or "sequences".
schema = Schema((int, float, basestring, SequenceValidator()))
schema.validate(first)
if not first:
raise ValueError("Cannot fit with no empty features")
# Build validation schema using the first data point
self.indexes = {} # Tuple index to matrix column mapping
self.reverse = [] # Matrix column to tuple index mapping
self.schema = [None] * len(first)
self.str_tuple_indexes = []
for i, data in enumerate(first):
if isinstance(data, (int, float)):
type_ = Use(float) # ints and floats are all mapped to float
self._add_column(i, None)
elif isinstance(data, basestring):
type_ = basestring # One-hot encoded indexes are added last
self.str_tuple_indexes.append(i)
else:
type_ = SequenceValidator(data)
for j in xrange(type_.size):
self._add_column(i, j)
self.schema[i] = type_
assert None not in self.schema
self.schema = tuple(self.schema)
self.validator = TupleValidator(self.schema)
示例3: _validate_neighbor
# 需要导入模块: from schema import Schema [as 别名]
# 或者: from schema.Schema import validate [as 别名]
def _validate_neighbor(self):
"""Validate neighbor against Schema."""
neighbor_schema = Schema({
'remote_ip': basestring,
'remote_as': And(basestring, lambda n: 0 <= int(n) <= 4294967295),
Optional('password'): basestring,
Optional('maximum_hops'): And(basestring,
lambda n: 1 <= int(n) <= 255),
Optional('timer_keepalive'): And(basestring,
lambda n: 1 <= int(n) <= 65535),
Optional('timer_timeout'): And(basestring,
lambda n: 3 <= int(n) <= 65536),
Optional('description'): basestring,
Optional('soft_reconfiguration'): bool,
Optional('community'): bool,
Optional('remove_private_as'): bool,
Optional('next_hop_self'): bool
})
try:
neighbor_schema.validate(self.neighbor)
except SchemaWrongKeyError:
# It doesn't matter if neighbor dict has other keys besides these.
pass
except SchemaError as e:
raise InvalidNeighborException(e.code)
示例4: validate_args
# 需要导入模块: from schema import Schema [as 别名]
# 或者: from schema.Schema import validate [as 别名]
def validate_args(args):
""" Validate arguments.
Checks:
that the specified file exists and is readable
that LEVEL is between 1 and 7
"""
schema = Schema({
"FILE": Use(open,
error="FILE doesn't exist or isn't readable!"),
"--level": Or(None,
And(Use(int), lambda n: 1 <= n <= 7),
error="LEVEL should be between 1 and 7"),
Optional("--help"): Or(True, False),
})
try:
# Don't return the validated args here, just make sure they are valid.
# Schema will return an object containing an open file object,
# when we just wanted to make sure the file was readable.
schema.validate(args)
return args
except SchemaError as e:
exit(e)
示例5: test_issue_56_cant_rely_on_callables_to_have_name
# 需要导入模块: from schema import Schema [as 别名]
# 或者: from schema.Schema import validate [as 别名]
def test_issue_56_cant_rely_on_callables_to_have_name():
s = Schema(methodcaller("endswith", ".csv"))
assert s.validate("test.csv") == "test.csv"
with SE:
try:
s.validate("test.py")
except SchemaError as e:
assert "operator.methodcaller" in e.args[0]
raise
示例6: test_missing_keys_exception_with_non_str_dict_keys
# 需要导入模块: from schema import Schema [as 别名]
# 或者: from schema.Schema import validate [as 别名]
def test_missing_keys_exception_with_non_str_dict_keys():
s = Schema({And(str, Use(str.lower), 'name'): And(str, len)})
with SE: s.validate(dict())
with SE:
try:
Schema({1: 'x'}).validate(dict())
except SchemaMissingKeyError as e:
assert e.args[0] == "Missing keys: 1"
raise
示例7: test_exception_handling_with_bad_validators
# 需要导入模块: from schema import Schema [as 别名]
# 或者: from schema.Schema import validate [as 别名]
def test_exception_handling_with_bad_validators():
BadValidator = namedtuple("BadValidator", ["validate"])
s = Schema(BadValidator("haha"))
with SE:
try:
s.validate("test")
except SchemaError as e:
assert "TypeError" in e.args[0]
raise
示例8: test_issue_9_prioritized_key_comparison_in_dicts
# 需要导入模块: from schema import Schema [as 别名]
# 或者: from schema.Schema import validate [as 别名]
def test_issue_9_prioritized_key_comparison_in_dicts():
# http://stackoverflow.com/questions/14588098/docopt-schema-validation
s = Schema({'ID': Use(int, error='ID should be an int'),
'FILE': Or(None, Use(open, error='FILE should be readable')),
Optional(str): object})
data = {'ID': 10, 'FILE': None, 'other': 'other', 'other2': 'other2'}
assert s.validate(data) == data
data = {'ID': 10, 'FILE': None}
assert s.validate(data) == data
示例9: Field
# 需要导入模块: from schema import Schema [as 别名]
# 或者: from schema.Schema import validate [as 别名]
class Field(BaseField):
NODEFAULT = object()
def __init__(self, schema_definition, mandatory=False, default=NODEFAULT):
self.validator = Schema(schema_definition)
self.mandatory = mandatory
self.default = default
def validate(self, data):
self.validator.validate(unfreeze(data))
示例10: test_issue_9_prioritized_key_comparison_in_dicts
# 需要导入模块: from schema import Schema [as 别名]
# 或者: from schema.Schema import validate [as 别名]
def test_issue_9_prioritized_key_comparison_in_dicts():
# http://stackoverflow.com/questions/14588098/docopt-schema-validation
s = Schema(
{
"ID": Use(int, error="ID should be an int"),
"FILE": Or(None, Use(open, error="FILE should be readable")),
Optional(str): object,
}
)
data = {"ID": 10, "FILE": None, "other": "other", "other2": "other2"}
assert s.validate(data) == data
data = {"ID": 10, "FILE": None}
assert s.validate(data) == data
示例11: test_test
# 需要导入模块: from schema import Schema [as 别名]
# 或者: from schema.Schema import validate [as 别名]
def test_test():
def unique_list(_list):
return len(_list) == len(set(_list))
def dict_keys(key, _list):
return list(map(lambda d: d[key], _list))
schema = Schema(Const(And(Use(partial(dict_keys, "index")), unique_list)))
data = [{"index": 1, "value": "foo"}, {"index": 2, "value": "bar"}]
assert schema.validate(data) == data
bad_data = [{"index": 1, "value": "foo"}, {"index": 1, "value": "bar"}]
with SE:
schema.validate(bad_data)
示例12: strategy
# 需要导入模块: from schema import Schema [as 别名]
# 或者: from schema.Schema import validate [as 别名]
def strategy(o):
'''Validates the the strategy object looks like a valid cassandra strategy'''
if not o or not isinstance(o, dict):
return False
o = copy.deepcopy(o)
clasz = o.get("class", None)
del o["class"]
if clasz == "SimpleStrategy":
validator = Schema({"replication_factor": int})
return bool(validator.validate(o))
elif clasz == "NetworkTopologyStrategy":
validator = Schema({str : int})
return bool(validator.validate(o))
else:
return False
示例13: parse_args
# 需要导入模块: from schema import Schema [as 别名]
# 或者: from schema.Schema import validate [as 别名]
def parse_args():
opts = docopt(__doc__, version='.'.join(VERSION))
schema = Schema({
Optional('PACK_TYPE'):
Or(None, lambda s: s.lower() in PACKS_TYPE,
error="PACK_TYPE should be either %s" % (', '.join(PACKS_TYPE))),
Optional('--config'):
Or(None, Use(open),
error="--config must be a readable file"),
Optional('--attempts'):
And(Use(int), lambda n: n > 0,
error='--attempts must be a strictly positive integer'),
Optional('--score'):
And(Use(int),
error='--score must be an integer'),
Optional('--threshold'):
And(Use(int), lambda n: n >= 0,
error='--threshold must be a positive integer'),
Optional('--low-threshold'):
And(Use(int), lambda n: n > 0,
error='--low-threshold must be a strictly positive integer'),
Optional('--wait'):
And(Use(int), lambda n: n >= 0,
error='--wait must be a positive integer'),
object: object,
})
opts = schema.validate(opts)
opts['PACK_TYPE'] = opts['PACK_TYPE'].lower() if opts['PACK_TYPE'] else "wild"
if opts['--config']:
config = simplejson.loads(opts['--config'].read())
opts.update(config)
return opts
示例14: Config
# 需要导入模块: from schema import Schema [as 别名]
# 或者: from schema.Schema import validate [as 别名]
class Config():
"""Configuration file
Its role's very simple, to load
a YAML file, validate it and from there
set options to be used by this program
"""
def __init__(self, *, config_file):
"""Constructor
:param config_file: path to configuration file
"""
# Default set of options
self._options = {
'hourly': True,
'monthly': True,
'tags': None,
'cpus': None,
'memory': None,
'hostname': None,
'domain': None,
'local_disk': None,
'datacenter': None,
'nic_speed': None,
'public_ip': None,
'private_ip': None
}
# Validation schema for each option
self._schema = Schema({
Optional('hourly'): bool,
Optional('monthly'): bool,
Optional('tags'): lambda tags: isinstance(tags, list)
and all([isinstance(t, str) for t in tags]),
Optional('cpus'): int,
Optional('memory'): int,
Optional('hostname'): str,
Optional('domain'): str,
Optional('local_disk'): str,
Optional('datacenter'): str,
Optional('nic_speed'): int,
Optional('public_ip'): str,
Optional('private_ip'): str
})
# Load YAML file and validate it
with open(config_file, "r") as file:
data = self._schema.validate(yaml.load(file))
for key, value in data.items():
# overwrite defaults with values taken
# from the configuration file
if key in self._options:
self._options[key] = value
@property
def options(self):
"""Get the whole options set"""
return self._options
示例15: test_generate_signature_schema
# 需要导入模块: from schema import Schema [as 别名]
# 或者: from schema.Schema import validate [as 别名]
def test_generate_signature_schema():
"""Test generate_signature_schema() function."""
def f(a, b, camelCase=True, none=None, quantity=3.0*unit.angstroms):
pass
f_schema = generate_signature_schema(f)
assert len(f_schema) == 3
for k in f_schema.keys():
assert isinstance(k, Optional)
# Remove Optional() marker for comparison
stripped_schema = {k._schema: v for k, v in f_schema.items() if k._schema != 'quantity'}
assert {'camel_case': bool, 'none': object} == stripped_schema
# Check conversion
f_schema = Schema(f_schema)
assert f_schema.validate({'quantity': '5*angstrom'}) == {'quantity': 5*unit.angstrom}
# Check update
optional_instance = Optional('camel_case')
updated_schema = generate_signature_schema(f, update_keys={'none': float, optional_instance: int},
exclude_keys={'quantity'})
assert len(updated_schema) == 2
assert updated_schema['none'] == float
assert updated_schema[optional_instance] == int