本文整理汇总了Python中voluptuous.Schema类的典型用法代码示例。如果您正苦于以下问题:Python Schema类的具体用法?Python Schema怎么用?Python Schema使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Schema类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_schema_extend_overrides
def test_schema_extend_overrides():
"""Verify that Schema.extend can override required/extra parameters."""
base = Schema({'a': int}, required=True)
extended = base.extend({'b': str}, required=False, extra=voluptuous.ALLOW_EXTRA)
assert base.required == True
assert base.extra == voluptuous.PREVENT_EXTRA
assert extended.required == False
assert extended.extra == voluptuous.ALLOW_EXTRA
示例2: test_subschema_extension
def test_subschema_extension():
"""Verify that Schema.extend adds and replaces keys in a subschema"""
base = Schema({'a': {'b': int, 'c': float}})
extension = {'d': str, 'a': {'b': str, 'e': int}}
extended = base.extend(extension)
assert_equal(base.schema, {'a': {'b': int, 'c': float}})
assert_equal(extension, {'d': str, 'a': {'b': str, 'e': int}})
assert_equal(extended.schema, {'a': {'b': str, 'c': float, 'e': int}, 'd': str})
示例3: test_schema_extend_key_swap
def test_schema_extend_key_swap():
"""Verify that Schema.extend can replace keys, even when different markers are used"""
base = Schema({Optional('a'): int})
extension = {Required('a'): int}
extended = base.extend(extension)
assert_equal(len(base.schema), 1)
assert_true(isinstance(list(base.schema)[0], Optional))
assert_equal(len(extended.schema), 1)
assert_true((list(extended.schema)[0], Required))
示例4: test_schema_extend
def test_schema_extend():
"""Verify that Schema.extend copies schema keys from both."""
base = Schema({'a': int}, required=True)
extension = {'b': str}
extended = base.extend(extension)
assert base.schema == {'a': int}
assert extension == {'b': str}
assert extended.schema == {'a': int, 'b': str}
assert extended.required == base.required
assert extended.extra == base.extra
示例5: test_schema_infer_list
def test_schema_infer_list():
schema = Schema.infer({
'list': ['foo', True, 42, 3.14]
})
assert_equal(schema, Schema({
Required('list'): [str, bool, int, float]
}))
示例6: test_schema_infer_scalar
def test_schema_infer_scalar():
assert_equal(Schema.infer('foo'), Schema(str))
assert_equal(Schema.infer(True), Schema(bool))
assert_equal(Schema.infer(42), Schema(int))
assert_equal(Schema.infer(3.14), Schema(float))
assert_equal(Schema.infer({}), Schema(dict))
assert_equal(Schema.infer([]), Schema(list))
示例7: test_schema_infer
def test_schema_infer():
schema = Schema.infer({
'str': 'foo',
'bool': True,
'int': 42,
'float': 3.14
})
assert_equal(schema, Schema({
Required('str'): str,
Required('bool'): bool,
Required('int'): int,
Required('float'): float
}))
示例8: __call__
def __call__(self, data):
_data = data.copy()
popped = []
for k, v in six.iteritems(data):
if v is None and k not in self._not_none:
_data.pop(k)
popped.append((k, v))
schema_out = Schema.__call__(self, _data)
for k, v in popped:
schema_out[k] = v
return schema_out
示例9: test_schema_infer_dict
def test_schema_infer_dict():
schema = Schema.infer({
'a': {
'b': {
'c': 'foo'
}
}
})
assert_equal(schema, Schema({
Required('a'): {
Required('b'): {
Required('c'): str
}
}
}))
示例10: test_schema_infer_accepts_kwargs
def test_schema_infer_accepts_kwargs():
schema = Schema.infer({
'str': 'foo',
'bool': True
}, required=False, extra=True)
# Subset of schema should be acceptable thanks to required=False.
schema({'bool': False})
# Keys that are in schema should still match required types.
try:
schema({'str': 42})
except Invalid:
pass
else:
assert False, 'Did not raise Invalid for Number'
# Extra fields should be acceptable thanks to extra=True.
schema({'str': 'bar', 'int': 42})
示例11: __init__
def __init__(self, schema, required=False, extra=False, not_none=False):
if not isinstance(schema, dict):
raise ValueError('This special Schema is intented to be used with '
'dict only.')
Schema.__init__(self, schema, required, extra)
self._not_none = not_none if not_none is not False else ()
示例12: Schema
#!/usr/bin/env python
__all__ = [
"Environment", "EnvironmentalDataPoint", "FirmwareModule",
"FirmwareModuleType", "Recipe", "SoftwareModule", "SoftwareModuleType"
]
from openag_lib.firmware.categories import SENSORS, ACTUATORS, CALIBRATION, all_categories
from voluptuous import Schema, Required, Any, Extra, Optional, REMOVE_EXTRA
Environment = Schema({
"name": Any(str, unicode),
}, extra=REMOVE_EXTRA)
Environment.__doc__ = """
An :class:`Environment` abstractly represents a single homogenous
climate-controlled volume within a system. A food computer usually consists of
a single :class:`Environment`, but larger systems will often contain more than
one :class:`Environment`.
.. py:attribute:: name
(str) A human-readable name for the environment
"""
EnvironmentalDataPoint = Schema({
Required("environment"): Any(str, unicode),
Required("variable"): Any(str, unicode),
Required("is_manual", default=False): bool,
Required("is_desired"): bool,
"value": object,
Required("timestamp"): Any(float, int),
}, extra=REMOVE_EXTRA)
示例13: test_generator_signing_balrog_tasks
def test_generator_signing_balrog_tasks(self):
for p in ("win32", "macosx64"):
for v, appV in (("38.0build1", "38.0"), ("37.0build2", "37.0")):
generator = get_task_by_name(self.graph, "{}_en-US_{}_funsize_update_generator".format(p, v))
signing = get_task_by_name(self.graph, "{}_en-US_{}_funsize_signing_task".format(p, v))
balrog = get_task_by_name(self.graph, "{}_en-US_{}_funsize_balrog_task".format(p, v))
generator_schema = Schema({
'requires': [self.generator_image['taskId']],
'task': {
'metadata': {
'name': "[funsize] Update generating task %s %s for %s" % (p, "en-US", v.split('build')[0],)
}
}
}, extra=True, required=True)
signing_schema = Schema({
'requires': [generator['taskId']],
'task': {
'metadata': {
'name': "[funsize] MAR signing task %s %s for %s" % (p, "en-US", v.split('build')[0],),
},
'payload': {
'signingManifest': "https://queue.taskcluster.net/v1/task/%s/artifacts/public/env/manifest.json" % generator["taskId"],
},
'scopes': [
"project:releng:signing:cert:release-signing",
"project:releng:signing:format:mar",
"project:releng:signing:format:gpg",
],
},
}, extra=True, required=True)
balrog_schema = Schema({
'requires': [signing['taskId'], self.funsize_balrog_image['taskId']],
'task': {
'scopes': ["docker-worker:feature:balrogVPNProxy"],
'metadata': {
'name': "[funsize] Publish to Balrog %s %s for %s" % (p, "en-US", v.split('build')[0],),
}
}
}, extra=True, required=True)
if p == "win32":
generator_schema = generator_schema.extend({
'task': {
'extra': {
'funsize': {
'partials': [
{
'from_mar': "http://download.mozilla.org/?product=firefox-%s-complete&os=win&lang=en-US" % appV,
'to_mar': "https://queue.taskcluster.net/v1/task/xyy/artifacts/public/build/firefox-42.0.en-US.win32.complete.mar",
}
]
}
}
}
})
elif p == "macosx64":
generator_schema = generator_schema.extend({
'task': {
'extra': {
'funsize': {
'partials': [
{
'from_mar': "http://download.mozilla.org/?product=firefox-%s-complete&os=osx&lang=en-US" % appV,
'to_mar': "https://queue.taskcluster.net/v1/task/xyz/artifacts/public/build/firefox-42.0.en-US.mac.complete.mar",
}
]
}
}
}
})
verify(generator, generator_schema, TestEnUSPartials.generator_not_allowed)
verify(balrog, balrog_schema)
verify(signing, signing_schema)
示例14: can_approve
@coroutine
def can_approve(self, user, **data):
"""
Only sys admins can approve an organisation, or a reseller sending pre_verified=true
:param user: a User
:param data: data that the user wants to update
"""
is_admin = user.is_admin()
is_reseller_preverifying = user.is_reseller() and data.get('pre_verified', False)
raise Return(is_admin or is_reseller_preverifying)
all_permission_schema = Schema({
'type': 'all',
'permission': In(PERMISSIONS),
'value': None
}, required=True)
organisation_permission_schema = all_permission_schema.extend({
'type': 'organisation_id',
'permission': In(PERMISSIONS),
'value': unicode
})
service_type_permission_schema = all_permission_schema.extend({
'type': 'service_type',
'permission': In(PERMISSIONS),
'value': In(SERVICE_TYPES)
})
def group_permissions(permissions):
示例15: parse_datetime
date = parse_datetime(value) or parse_date(value)
if date is not None:
return date
else:
raise ValueError
except ValueError:
raise Invalid('<{0}> is not a valid datetime.'.format(value))
return fn
base_query_param_schema = Schema(
{
'q': str,
'name': str,
'offset': IntegerLike(),
'limit': IntegerLike(),
'install_ts': DatetimeWithTZ(),
'update_ts': DatetimeWithTZ()
},
extra=ALLOW_EXTRA
)
company_query_schema = base_query_param_schema.extend(
{
"id": IntegerLike(),
"name": str,
"description": str,
"auction_id": CSVofIntegers(), # /?team_id=1,2,3
}
)