Python voluptuous.Coerce() Examples

The following are 14 code examples of voluptuous.Coerce(). 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: test_settings.py    From armi with Apache License 2.0 6 votes vote down vote up
def test_typeDetection(self):
        """Ensure some of the type inference operations work."""
        listSetting = setting.Setting(
            "aList",
            default=[],
            label="label",
            description="desc",
            schema=vol.Schema([float]),
        )
        self.assertEqual(listSetting.containedType, float)
        listSetting = setting.Setting(
            "aList",
            default=[],
            label="label",
            description="desc",
            schema=vol.Schema([vol.Coerce(float)]),
        )
        self.assertEqual(listSetting.containedType, float) 
Example #2
Source File: setting.py    From armi with Apache License 2.0 6 votes vote down vote up
def _setSchema(self, schema):
        """Apply or auto-derive schema of the value."""
        if schema:
            self.schema = schema
        elif self.options and self.enforcedOptions:
            self.schema = vol.Schema(vol.In(self.options))
        else:
            # Coercion is needed to convert XML-read migrations (for old cases)
            # as well as in some GUI instances where lists are getting set
            # as strings.
            if isinstance(self.default, list) and self.default:
                # Non-empty default: assume the default has the desired contained type
                # Coerce all values to the first entry in the default so mixed floats and ints work.
                # Note that this will not work for settings that allow mixed
                # types in their lists (e.g. [0, '10R']), so those all need custom schemas.
                self.schema = vol.Schema([vol.Coerce(type(self.default[0]))])
            else:
                self.schema = vol.Schema(vol.Coerce(type(self.default))) 
Example #3
Source File: api.py    From gnocchi with Apache License 2.0 5 votes vote down vote up
def get_pagination_options(params, default):
    try:
        opts = voluptuous.Schema({
            voluptuous.Required(
                "limit", default=pecan.request.conf.api.max_limit):
            voluptuous.All(voluptuous.Coerce(int),
                           voluptuous.Range(min=1),
                           voluptuous.Clamp(
                               min=1, max=pecan.request.conf.api.max_limit)),
            "marker": six.text_type,
            voluptuous.Required("sort", default=default):
            voluptuous.All(
                voluptuous.Coerce(arg_to_list),
                [six.text_type]),
        }, extra=voluptuous.REMOVE_EXTRA)(params)
    except voluptuous.Invalid as e:
        abort(400, {"cause": "Argument value error",
                    "reason": str(e)})
    opts['sorts'] = opts['sort']
    del opts['sort']
    return opts 
Example #4
Source File: api.py    From gnocchi with Apache License 2.0 5 votes vote down vote up
def post(self):
        enforce("create archive policy", {})
        # NOTE(jd): Initialize this one at run-time because we rely on conf
        conf = pecan.request.conf
        valid_agg_methods = list(
            archive_policy.ArchivePolicy.VALID_AGGREGATION_METHODS_VALUES
        )
        ArchivePolicySchema = voluptuous.Schema({
            voluptuous.Required("name"): six.text_type,
            voluptuous.Required("back_window", default=0): voluptuous.All(
                voluptuous.Coerce(int),
                voluptuous.Range(min=0),
            ),
            voluptuous.Required(
                "aggregation_methods",
                default=list(conf.archive_policy.default_aggregation_methods)):
            valid_agg_methods,
            voluptuous.Required("definition"): ArchivePolicyDefinitionSchema,
        })

        body = deserialize_and_validate(ArchivePolicySchema)
        # Validate the data
        try:
            ap = archive_policy.ArchivePolicy.from_dict(body)
        except ValueError as e:
            abort(400, six.text_type(e))
        enforce("create archive policy", ap)
        try:
            ap = pecan.request.indexer.create_archive_policy(ap)
        except indexer.ArchivePolicyAlreadyExists as e:
            abort(409, six.text_type(e))

        location = "/archive_policy/" + ap.name
        set_resp_location_hdr(location)
        pecan.response.status = 201
        return ap 
Example #5
Source File: __init__.py    From mergify-engine with Apache License 2.0 5 votes vote down vote up
def get_schema(cls):
        return voluptuous.All(cls.validator, voluptuous.Coerce(cls)) 
Example #6
Source File: setting.py    From armi with Apache License 2.0 5 votes vote down vote up
def containedType(self):
        """The subtype for lists."""
        # assume schema set to [int] or [str] or something similar
        try:
            containedSchema = self.schema.schema[0]
            if isinstance(containedSchema, vol.Coerce):
                # special case for Coerce objects, which
                # store their underlying type as ``.type``.
                return containedSchema.type
            return containedSchema
        except TypeError:
            # cannot infer. fall back to str
            return str 
Example #7
Source File: test_schema.py    From lxdock with GNU General Public License v3.0 5 votes vote down vote up
def test_can_validate_and_coerce_multiple_provisioner_schemas(self, mock_Provisioner):
        mock_Provisioner.provisioners = {
            'mp1': MockProvisioner1,
            'mp2': MockProvisioner2,
            'mp3': MockProvisioner3}
        schema = get_schema()
        validated = schema({
            'name': 'dummy-test',
            'provisioning': [{
                'type': 'mp1',
                'a': 'dummy',
                'b': '16'
            }, {
                'type': 'mp2',
                'a': 'dummy',
            }, {
                'type': 'mp3',
                'b': 'yes'
            }]
        })
        assert validated == {
            'name': 'dummy-test',
            'provisioning': [{
                'type': 'mp1',
                'a': 'dummy',
                'b': 16  # Check Coerce
            }, {
                'type': 'mp2',
                'a': 'dummy',
            }, {
                'type': 'mp3',
                'b': True  # Check Boolean
            }]
        } 
Example #8
Source File: utils.py    From cloudkitty with Apache License 2.0 5 votes vote down vote up
def __init__(self, param_type):
        self._validate = voluptuous.Coerce(param_type) 
Example #9
Source File: utils.py    From cloudkitty with Apache License 2.0 5 votes vote down vote up
def __init__(self, param_type):
        self._validate = lambda x: list(map(voluptuous.Coerce(param_type), x)) 
Example #10
Source File: utils.py    From cloudkitty with Apache License 2.0 5 votes vote down vote up
def __init__(self, key_type, val_type, unique_values=True):
        self._kval = voluptuous.Coerce(key_type)
        self._unique_val = unique_values

        if self._unique_val:
            self._vval = voluptuous.Coerce(val_type)
        else:
            def __vval(values):
                return [voluptuous.Coerce(val_type)(v) for v in values]
            self._vval = __vval 
Example #11
Source File: validation.py    From cloudkitty with Apache License 2.0 5 votes vote down vote up
def __init__(self, key_type, value_type, cast=True):
        if cast:
            self._kval = voluptuous.Coerce(key_type)
            self._vval = voluptuous.Coerce(value_type)
        else:
            def __type_validator(type_, elem):
                if not isinstance(elem, type_):
                    raise voluptuous.Invalid(
                        "{e} is not of type {t}".format(e=elem, t=type_))
                return elem

            self._kval = functools.partial(__type_validator, key_type)
            self._vval = functools.partial(__type_validator, value_type) 
Example #12
Source File: validation.py    From pymysensors with MIT License 5 votes vote down vote up
def is_heartbeat(value):
    """Validate that value is a valid heartbeat integer."""
    try:
        value = vol.Coerce(int)(value)
        return value
    except vol.Invalid:
        _LOGGER.warning(
            "%s is not a valid heartbeat value, falling back to heartbeat 0", value
        )
        return 0 
Example #13
Source File: const_20.py    From pymysensors with MIT License 5 votes vote down vote up
def validate_gps(value):
    """Validate GPS value."""
    try:
        latitude, longitude, altitude = value.split(",")
        vol.Coerce(float)(latitude)
        vol.Coerce(float)(longitude)
        vol.Coerce(float)(altitude)
    except (TypeError, ValueError, vol.Invalid):
        raise vol.Invalid('GPS value should be of format "latitude,longitude,altitude"')
    return value 
Example #14
Source File: test_voluptuous.py    From pydantic with MIT License 5 votes vote down vote up
def __init__(self, allow_extra):
        self.schema = v.Schema(
            {
                v.Required('id'): int,
                v.Required('client_name'): v.All(str, v.Length(max=255)),
                v.Required('sort_index'): float,
                # v.Optional('client_email'): v.Maybe(v.Email),
                v.Optional('client_phone'): v.Maybe(v.All(str, v.Length(max=255))),
                v.Optional('location'): v.Maybe(
                    v.Schema(
                        {
                            'latitude': v.Maybe(float),
                            'longitude': v.Maybe(float)
                        },
                        required=True
                    )
                ),
                v.Optional('contractor'): v.Maybe(v.All(v.Coerce(int), v.Range(min=1))),
                v.Optional('upstream_http_referrer'): v.Maybe(v.All(str, v.Length(max=1023))),
                v.Required('grecaptcha_response'): v.All(str, v.Length(min=20, max=1000)),
                v.Optional('last_updated'): v.Maybe(parse_datetime),
                v.Required('skills', default=[]): [
                    v.Schema(
                        {
                            v.Required('subject'): str,
                            v.Required('subject_id'): int,
                            v.Required('category'): str,
                            v.Required('qual_level'): str,
                            v.Required('qual_level_id'): int,
                            v.Required('qual_level_ranking', default=0): float,
                        }
                    )
                ],
            },
            extra=allow_extra,
        )