Python voluptuous.Any() Examples

The following are 30 code examples of voluptuous.Any(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module voluptuous , or try the search function .
Example #1
Source File: config.py    From spid-testenv2 with GNU Affero General Public License v3.0 7 votes vote down vote up
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)),
            }
        } 
Example #2
Source File: config.py    From hass-apps with Apache License 2.0 6 votes vote down vote up
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 
Example #3
Source File: resource_type.py    From gnocchi with Apache License 2.0 6 votes vote down vote up
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))
            }
        }) 
Example #4
Source File: generic2.py    From hass-apps with Apache License 2.0 6 votes vote down vote up
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 
Example #5
Source File: thermostat.py    From hass-apps with Apache License 2.0 6 votes vote down vote up
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 
Example #6
Source File: stats.py    From hass-apps with Apache License 2.0 6 votes vote down vote up
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 
Example #7
Source File: generic.py    From hass-apps with Apache License 2.0 6 votes vote down vote up
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 
Example #8
Source File: template_syntax_validator_v3.py    From vitrage with Apache License 2.0 5 votes vote down vote up
def _parameters_schema():
    return Schema({
        any_str: Any(any_str, Schema({
            Optional(TF.DESCRIPTION): any_str,
            Optional(TF.DEFAULT): any_str,
        })),
    }) 
Example #9
Source File: template_syntax_validator_v3.py    From vitrage with Apache License 2.0 5 votes vote down vote up
def _scenarios_schema(template):

    return Schema([
        Schema({
            Required(TF.ACTIONS, msg=84): Schema([Any(
                _raise_alarm_schema(template),
                _set_state_schema(template),
                _add_causal_relationship_schema(template),
                _mark_down_schema(template),
                _execute_mistral_schema(),
            )]),
            Required(TF.CONDITION, msg=83): any_str,
        })]) 
Example #10
Source File: template_syntax_validator.py    From vitrage with Apache License 2.0 5 votes vote down vote up
def _validate_template_sections(template_conf):
    any_str = Any(str, six.text_type)
    paramsSchema = Schema({
        any_str: Any(any_str, Schema({
            Optional(TemplateFields.DESCRIPTION): any_str,
            Optional(TemplateFields.DEFAULT): any_str,
        })),
    })

    if TemplateFields.INCLUDES in template_conf:
        schema = Schema({
            Optional(TemplateFields.DEFINITIONS): dict,
            Required(TemplateFields.METADATA, msg=62): dict,
            Required(TemplateFields.SCENARIOS, msg=80): list,
            Optional(TemplateFields.INCLUDES): list,
            Optional(TemplateFields.PARAMETERS): paramsSchema,
        })
    else:
        schema = Schema({
            Required(TemplateFields.DEFINITIONS, msg=21): dict,
            Required(TemplateFields.METADATA, msg=62): dict,
            Required(TemplateFields.SCENARIOS, msg=80): list,
            Optional(TemplateFields.INCLUDES): list,
            Optional(TemplateFields.PARAMETERS): paramsSchema,
        })
    return _validate_dict_schema(schema, template_conf) 
Example #11
Source File: thermostat.py    From hass-apps with Apache License 2.0 5 votes vote down vote up
def validate_value(value: T.Any) -> Temp:
        """Ensures the given value is a valid temperature."""

        return Temp(value) 
Example #12
Source File: config.py    From hass-apps with Apache License 2.0 5 votes vote down vote up
def build_range_spec_validator(  # type: ignore
    min_value: int, max_value: int
) -> vol.Schema:
    """Returns a validator for range specifications with the given
    min/max values."""

    return vol.All(
        vol.Any(int, str), lambda v: util.expand_range_spec(v, min_value, max_value)
    ) 
Example #13
Source File: template_syntax_validator.py    From vitrage with Apache License 2.0 5 votes vote down vote up
def _validate_metadata_section(metadata):
    any_str = Any(str, six.text_type)

    schema = Schema({
        TemplateFields.VERSION: any_str,
        Required(TemplateFields.NAME, msg=60): any_str,
        TemplateFields.DESCRIPTION: any_str,
        TemplateFields.TYPE: any_str,
    })
    return _validate_dict_schema(schema, metadata) 
Example #14
Source File: stats.py    From hass-apps with Apache License 2.0 5 votes vote down vote up
def collect_values(  # pylint: disable=no-self-use
        self,
    ) -> T.Iterable[T.Tuple[T.Any, T.Union[float, int]]]:
        """Should collect the implementation-specific values from which
        entries are built. The first item of each tuple is an identifier
        for the value (e.g. an entity id of the entity it originated
        from), the second is the value."""

        return [] 
Example #15
Source File: stats.py    From hass-apps with Apache License 2.0 5 votes vote down vote up
def update_handler(
        self, *args: T.Any, **kwargs: T.Any  # pylint: disable=unused-argument
    ) -> None:
        """A convenience wrapper around self.update(), accepting any
        positional and wildcard argument. It is intended to be used
        with events that pass arguments to their handler we're not
        interested in."""

        self.update() 
Example #16
Source File: stats.py    From hass-apps with Apache License 2.0 5 votes vote down vote up
def log(self, msg: str, *args: T.Any, **kwargs: T.Any) -> None:
        """Prefixes the parameter to log messages."""

        msg = "[{}] {}".format(self, msg)
        self.app.log(msg, *args, **kwargs) 
Example #17
Source File: template_syntax_validator.py    From vitrage with Apache License 2.0 5 votes vote down vote up
def _validate_includes_section(includes):
    any_str = Any(str, six.text_type)
    if not includes:
        LOG.error('%s status code: %s' % (status_msgs[140], 140))
        return get_fault_result(RESULT_DESCRIPTION, 140)

    for name in includes:
        schema = Schema({
            Required(TemplateFields.NAME, msg=141): any_str
        })
        result = _validate_name_schema(schema, name)
        if not result.is_valid_config:
            return result

    return result 
Example #18
Source File: template_syntax_validator.py    From vitrage with Apache License 2.0 5 votes vote down vote up
def _validate_relationship_dict(relationship_dict):
    any_str = Any(str, six.text_type)
    schema = Schema({
        Required(TemplateFields.SOURCE, msg=102): any_str,
        Required(TemplateFields.TARGET, msg=103): any_str,
        Required(TemplateFields.RELATIONSHIP_TYPE, msg=100): any_str,
        Required(TemplateFields.TEMPLATE_ID, msg=104):
            All(_validate_template_id_value())
    })
    return _validate_dict_schema(schema, relationship_dict) 
Example #19
Source File: generic2.py    From hass-apps with Apache License 2.0 5 votes vote down vote up
def notify_state_changed(self, attrs: dict) -> T.Any:
        """Is called when the entity's state changes."""
        items = []
        for attr_cfg in self.cfg["attributes"]:
            attr = attr_cfg["attribute"]
            if attr is None:
                self.log("Ignoring state change (write-only attribute).", level="DEBUG")
                return None
            state = attrs.get(attr)
            self.log(
                "Attribute {!r} is {!r}.".format(attr, state),
                level="DEBUG",
                prefix=common.LOG_PREFIX_INCOMING,
            )
            if self.cfg["ignore_case"] and isinstance(state, str):
                state = state.lower()
            items.append(state)

        tpl = tuple(items)
        # Goes from len(tpl) down to 0
        for size in range(len(tpl), -1, -1):
            value = tpl[:size]
            try:
                self._find_value_cfg(value)
            except ValueError:
                continue
            return value

        self.log(
            "Received state {!r} which is not configured as a value.".format(items),
            level="WARNING",
        )
        return None 
Example #20
Source File: template_syntax_validator.py    From vitrage with Apache License 2.0 5 votes vote down vote up
def _validate_scenario(scenario):
    any_str = Any(str, six.text_type)
    schema = Schema({
        Required(TemplateFields.CONDITION, msg=83): any_str,
        Required(TemplateFields.ACTIONS, msg=84): list
    })
    result = _validate_dict_schema(schema, scenario)

    if result.is_valid_config:
        return _validate_actions_schema(scenario[TemplateFields.ACTIONS])

    return result 
Example #21
Source File: generic2.py    From hass-apps with Apache License 2.0 5 votes vote down vote up
def filter_set_value(self, value: T.Tuple) -> T.Any:
        """Checks whether the actor supports this value."""
        if self.cfg["ignore_case"]:
            value = tuple(v.lower() if isinstance(v, str) else v for v in value)
        try:
            self._find_value_cfg(value)
        except ValueError:
            self.log(
                "Value {!r} is not known by this actor.".format(value), level="ERROR"
            )
            return None
        return value 
Example #22
Source File: thermostat.py    From hass-apps with Apache License 2.0 5 votes vote down vote up
def __add__(self, other: T.Any) -> "Off":
        return self 
Example #23
Source File: api.py    From gnocchi with Apache License 2.0 5 votes vote down vote up
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:]) 
Example #24
Source File: api.py    From gnocchi with Apache License 2.0 5 votes vote down vote up
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) 
Example #25
Source File: api.py    From gnocchi with Apache License 2.0 5 votes vote down vote up
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 
Example #26
Source File: _importer.py    From tcconfig with MIT License 5 votes vote down vote up
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))
        ) 
Example #27
Source File: generic.py    From hass-apps with Apache License 2.0 5 votes vote down vote up
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) 
Example #28
Source File: generic2.py    From hass-apps with Apache License 2.0 5 votes vote down vote up
def _find_value_cfg(self, value: T.Tuple) -> T.Any:
        """Returns the config matching given value or ValueError if none found."""
        for value_cfg in self.cfg["values"]:
            _value = value_cfg["value"]
            if len(_value) != len(value):
                continue
            for idx, attr_value in enumerate(_value):
                if attr_value not in (WILDCARD_ATTRIBUTE_VALUE, value[idx]):
                    break
            else:
                return value_cfg
        raise ValueError("No configuration for value {!r}".format(value)) 
Example #29
Source File: thermostat.py    From hass-apps with Apache License 2.0 5 votes vote down vote up
def __sub__(self, other: T.Any) -> "Off":
        return self 
Example #30
Source File: thermostat.py    From hass-apps with Apache License 2.0 5 votes vote down vote up
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]