本文整理汇总了Python中voluptuous.Any方法的典型用法代码示例。如果您正苦于以下问题:Python voluptuous.Any方法的具体用法?Python voluptuous.Any怎么用?Python voluptuous.Any使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类voluptuous
的用法示例。
在下文中一共展示了voluptuous.Any方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: parse_temp
# 需要导入模块: import voluptuous [as 别名]
# 或者: from voluptuous import Any [as 别名]
def parse_temp(value: T.Any) -> T.Union[float, Off, None]:
"""Converts the given value to a valid temperature of type float
or Off.
If value is a string, all whitespace is removed first.
If conversion is not possible, None is returned."""
if isinstance(value, str):
value = "".join(value.split())
if value.upper() == "OFF":
return OFF
if isinstance(value, Off):
return OFF
try:
return float(value)
except (ValueError, TypeError):
return None
示例2: __init__
# 需要导入模块: import voluptuous [as 别名]
# 或者: from voluptuous import Any [as 别名]
def __init__(self, *args, **kwargs):
super(ResourceTypeSchemaManager, self).__init__(*args, **kwargs)
type_schemas = tuple([ext.plugin.meta_schema()
for ext in self.extensions])
self._schema = voluptuous.Schema({
"name": six.text_type,
voluptuous.Required("attributes", default={}): {
six.text_type: voluptuous.Any(*tuple(type_schemas))
}
})
type_schemas = tuple([ext.plugin.meta_schema(for_update=True)
for ext in self.extensions])
self._schema_for_update = voluptuous.Schema({
"name": six.text_type,
voluptuous.Required("attributes", default={}): {
six.text_type: voluptuous.Any(*tuple(type_schemas))
}
})
示例3: validate_value
# 需要导入模块: import voluptuous [as 别名]
# 或者: from voluptuous import Any [as 别名]
def validate_value(value: T.Any) -> T.Any:
"""Converts lists to tuples."""
if isinstance(value, list):
items = tuple(value)
elif isinstance(value, tuple):
items = value
else:
items = (value,)
for index, item in enumerate(items):
if not isinstance(item, ALLOWED_VALUE_TYPES):
raise ValueError(
"Value {} for slot {} must be of one of these types: {}".format(
repr(item), index, ALLOWED_VALUE_TYPES
)
)
return items[0] if len(items) == 1 else items
示例4: validate_value
# 需要导入模块: import voluptuous [as 别名]
# 或者: from voluptuous import Any [as 别名]
def validate_value(value: T.Any) -> T.Any:
"""Converts lists to tuples."""
if isinstance(value, list):
items = tuple(value)
elif isinstance(value, tuple):
items = value
else:
items = (value,)
for index, item in enumerate(items):
if not isinstance(item, ALLOWED_VALUE_TYPES):
raise ValueError(
"Value {!r} for {}. attribute must be of one of these types: "
"{}".format(item, index + 1, ALLOWED_VALUE_TYPES)
)
return items
示例5: collect_values
# 需要导入模块: import voluptuous [as 别名]
# 或者: from voluptuous import Any [as 别名]
def collect_values(self) -> T.Iterable[T.Tuple[T.Any, T.Union[float, int]]]:
"""Calls self.collect_actor_value() for all actors of the
associated rooms and returns the collected values."""
values = []
for room in self.rooms:
for actor in filter(lambda a: a.is_initialized, room.actors.values()):
value = self.collect_actor_value( # pylint: disable=assignment-from-none
actor
)
self.log(
"Value for {} in {} is {}.".format(actor, room, value),
level="DEBUG",
)
if value is not None:
values.append((actor.entity_id, value))
return values
示例6: parse_watched_entity_str
# 需要导入模块: import voluptuous [as 别名]
# 或者: from voluptuous import Any [as 别名]
def parse_watched_entity_str(value: str) -> T.Dict[str, T.Any]:
"""Parses the alternative <entity>:<attributes>:<mode> strings."""
obj = {} # type: T.Dict[str, T.Any]
spl = [part.strip() for part in value.split(":")]
if spl:
part = spl.pop(0)
if part:
obj["entity"] = part
if spl:
part = spl.pop(0)
if part:
obj["attributes"] = [_part.strip() for _part in part.split(",")]
if spl:
part = spl.pop(0)
if part:
obj["mode"] = part
return obj
示例7: _init_schema
# 需要导入模块: import voluptuous [as 别名]
# 或者: from voluptuous import Any [as 别名]
def _init_schema(self):
self._schema = {
Required('key_file'): str,
Required('cert_file'): str,
Required('base_url'): Url(),
'host': str,
'port': Any(int, str),
'debug': bool,
'https': bool,
'https_cert_file': str,
'https_key_file': str,
'users_file': str,
'behind_reverse_proxy': bool,
'can_add_user': bool,
'storage': All(str, In(['file', 'postgres'])),
'db_url': str,
'endpoints': {
'single_logout_service': str,
'single_sign_on_service': str,
},
'metadata': {
'local': All([str], Length(min=0)),
'remote': All([str], Length(min=0)),
}
}
示例8: MetricSchema
# 需要导入模块: import voluptuous [as 别名]
# 或者: from voluptuous import Any [as 别名]
def MetricSchema(v):
"""metric keyword schema
It could be:
["metric", "metric-ref", "aggregation"]
or
["metric, ["metric-ref", "aggregation"], ["metric-ref", "aggregation"]]
"""
if not isinstance(v, (list, tuple)):
raise voluptuous.Invalid("Expected a tuple/list, got a %s" % type(v))
elif not v:
raise voluptuous.Invalid("Operation must not be empty")
elif len(v) < 2:
raise voluptuous.Invalid("Operation need at least one argument")
elif v[0] != u"metric":
# NOTE(sileht): this error message doesn't looks related to "metric",
# but because that the last schema validated by voluptuous, we have
# good chance (voluptuous.Any is not predictable) to print this
# message even if it's an other operation that invalid.
raise voluptuous.Invalid("'%s' operation invalid" % v[0])
return [u"metric"] + voluptuous.Schema(voluptuous.Any(
voluptuous.ExactSequence([six.text_type, six.text_type]),
voluptuous.All(
voluptuous.Length(min=1),
[voluptuous.ExactSequence([six.text_type, six.text_type])],
)), required=True)(v[1:])
示例9: OperationsSchema
# 需要导入模块: import voluptuous [as 别名]
# 或者: from voluptuous import Any [as 别名]
def OperationsSchema(v):
if isinstance(v, six.text_type):
try:
v = pyparsing.OneOrMore(
pyparsing.nestedExpr()).parseString(v).asList()[0]
except pyparsing.ParseException as e:
api.abort(400, {"cause": "Invalid operations",
"reason": "Fail to parse the operations string",
"detail": six.text_type(e)})
return voluptuous.Schema(voluptuous.Any(*OperationsSchemaBase),
required=True)(v)
示例10: ResourceSchema
# 需要导入模块: import voluptuous [as 别名]
# 或者: from voluptuous import Any [as 别名]
def ResourceSchema(schema):
base_schema = {
voluptuous.Optional('started_at'): utils.to_datetime,
voluptuous.Optional('ended_at'): utils.to_datetime,
voluptuous.Optional('user_id'): voluptuous.Any(None, six.text_type),
voluptuous.Optional('project_id'): voluptuous.Any(None, six.text_type),
voluptuous.Optional('metrics'): MetricsSchema,
}
base_schema.update(schema)
return base_schema
示例11: load_tcconfig
# 需要导入模块: import voluptuous [as 别名]
# 或者: from voluptuous import Any [as 别名]
def load_tcconfig(self, config_file_path):
from voluptuous import Schema, Required, Any, ALLOW_EXTRA
schema = Schema(
{Required(str): {Any(*TrafficDirection.LIST): {str: {str: Any(str, int, float)}}}},
extra=ALLOW_EXTRA,
)
with open(config_file_path, encoding="utf-8") as fp:
self.__config_table = json.load(fp)
schema(self.__config_table)
self.__logger.debug(
"tc config file: {:s}".format(json.dumps(self.__config_table, indent=4))
)
示例12: do_send
# 需要导入模块: import voluptuous [as 别名]
# 或者: from voluptuous import Any [as 别名]
def do_send(self) -> None:
"""Executes the services configured for self._wanted_value."""
value = self._wanted_value
if not isinstance(value, tuple):
value = (value,)
iterator = enumerate(value) # type: T.Iterator[T.Tuple[int, T.Any]]
if self.cfg["call_reversed"]:
iterator = reversed(list(iterator))
for index, item in iterator:
_, cfg = self._get_value_cfg(index, item)
service = cfg["service"]
service_data = cfg["service_data"].copy()
if cfg["include_entity_id"]:
service_data.setdefault("entity_id", self.entity_id)
if cfg["value_parameter"] is not None:
service_data.setdefault(cfg["value_parameter"], item)
self.log(
"Calling service {}, data = {}.".format(
repr(service), repr(service_data)
),
level="DEBUG",
prefix=common.LOG_PREFIX_OUTGOING,
)
self.app.call_service(service, **service_data)
示例13: __add__
# 需要导入模块: import voluptuous [as 别名]
# 或者: from voluptuous import Any [as 别名]
def __add__(self, other: T.Any) -> "Off":
return self
示例14: __sub__
# 需要导入模块: import voluptuous [as 别名]
# 或者: from voluptuous import Any [as 别名]
def __sub__(self, other: T.Any) -> "Off":
return self
示例15: __init__
# 需要导入模块: import voluptuous [as 别名]
# 或者: from voluptuous import Any [as 别名]
def __init__(self, temp_value: T.Any) -> None:
if isinstance(temp_value, Temp):
# Just copy the value over.
parsed = self.parse_temp(temp_value.value)
else:
parsed = self.parse_temp(temp_value)
if parsed is None:
raise ValueError("{} is no valid temperature".format(repr(temp_value)))
self.value = parsed # type: T.Union[float, Off]