当前位置: 首页>>代码示例>>Python>>正文


Python voluptuous.Schema方法代码示例

本文整理汇总了Python中voluptuous.Schema方法的典型用法代码示例。如果您正苦于以下问题:Python voluptuous.Schema方法的具体用法?Python voluptuous.Schema怎么用?Python voluptuous.Schema使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在voluptuous的用法示例。


在下文中一共展示了voluptuous.Schema方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: __init__

# 需要导入模块: import voluptuous [as 别名]
# 或者: from voluptuous import Schema [as 别名]
def __init__(self, type, name, required, options=None):
        if (len(name) > 63 or name in INVALID_NAMES
                or not VALID_CHARS.match(name)):
            raise InvalidResourceAttributeName(name)

        self.name = name
        self.required = required
        self.fill = None

        # options is set only when we update a resource type
        if options is not None:
            fill = options.get("fill")
            if fill is None and required:
                raise InvalidResourceAttributeOption(
                    name, "fill", "must not be empty if required=True")
            elif fill is not None:
                # Ensure fill have the correct attribute type
                try:
                    self.fill = voluptuous.Schema(self.schema_ext)(fill)
                except voluptuous.Error as e:
                    raise InvalidResourceAttributeOption(name, "fill", e) 
开发者ID:gnocchixyz,项目名称:gnocchi,代码行数:23,代码来源:resource_type.py

示例2: patch

# 需要导入模块: import voluptuous [as 别名]
# 或者: from voluptuous import Schema [as 别名]
def patch(self):
        ap = pecan.request.indexer.get_archive_policy(self.archive_policy)
        if not ap:
            abort(404, six.text_type(
                indexer.NoSuchArchivePolicy(self.archive_policy)))
        enforce("update archive policy", ap)

        body = deserialize_and_validate(voluptuous.Schema({
            voluptuous.Required("definition"): ArchivePolicyDefinitionSchema,
        }))
        # Validate the data
        try:
            ap_items = [archive_policy.ArchivePolicyItem(**item) for item in
                        body['definition']]
        except ValueError as e:
            abort(400, six.text_type(e))

        try:
            return pecan.request.indexer.update_archive_policy(
                self.archive_policy, ap_items)
        except indexer.UnsupportedArchivePolicyChange as e:
            abort(400, six.text_type(e)) 
开发者ID:gnocchixyz,项目名称:gnocchi,代码行数:24,代码来源:api.py

示例3: post

# 需要导入模块: import voluptuous [as 别名]
# 或者: from voluptuous import Schema [as 别名]
def post(self):
        enforce("create archive policy rule", {})
        ArchivePolicyRuleSchema = voluptuous.Schema({
            voluptuous.Required("name"): six.text_type,
            voluptuous.Required("metric_pattern"): six.text_type,
            voluptuous.Required("archive_policy_name"): six.text_type,
            })

        body = deserialize_and_validate(ArchivePolicyRuleSchema)
        enforce("create archive policy rule", body)
        try:
            ap = pecan.request.indexer.create_archive_policy_rule(
                body['name'], body['metric_pattern'],
                body['archive_policy_name']
            )
        except indexer.ArchivePolicyRuleAlreadyExists as e:
            abort(409, six.text_type(e))
        except indexer.NoSuchArchivePolicy as e:
            abort(400, e)

        location = "/archive_policy_rule/" + ap.name
        set_resp_location_hdr(location)
        pecan.response.status = 201
        return ap 
开发者ID:gnocchixyz,项目名称:gnocchi,代码行数:26,代码来源:api.py

示例4: validate_config

# 需要导入模块: import voluptuous [as 别名]
# 或者: from voluptuous import Schema [as 别名]
def validate_config(_config):
        source_schema = voluptuous.Schema({
            "module": voluptuous.And(six.string_types[0],
                                     vu.NoSpaceCharacter()),
            "params": {
                "zk_host": voluptuous.And(six.string_types[0],
                                          vu.NoSpaceCharacter()),
                "zk_port": int,
                "group_id": voluptuous.And(six.string_types[0],
                                           vu.NoSpaceCharacter()),
                "topics": {
                    voluptuous.And(six.string_types[0],
                                   vu.NoSpaceCharacter()):
                    voluptuous.And(int, voluptuous.Range(min=1))
                }
            }
        }, required=True)
        return source_schema(_config) 
开发者ID:openstack,项目名称:monasca-analytics,代码行数:20,代码来源:kafka.py

示例5: test_typeDetection

# 需要导入模块: import voluptuous [as 别名]
# 或者: from voluptuous import Schema [as 别名]
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) 
开发者ID:terrapower,项目名称:armi,代码行数:20,代码来源:test_settings.py

示例6: _setSchema

# 需要导入模块: import voluptuous [as 别名]
# 或者: from voluptuous import Schema [as 别名]
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))) 
开发者ID:terrapower,项目名称:armi,代码行数:20,代码来源:setting.py

示例7: async_step_user

# 需要导入模块: import voluptuous [as 别名]
# 或者: from voluptuous import Schema [as 别名]
def async_step_user(self, user_input=None):
        if self._async_current_entries():
            return self.async_abort(reason="single_instance_allowed")
        if self.hass.data.get(DOMAIN):
            return self.async_abort(reason="single_instance_allowed")

        errors = {}

        fields = OrderedDict()
        fields[vol.Optional(CONF_PORT)] = str

        if user_input is not None:
            print(user_input)
            return self.async_create_entry(title=user_input.get(CONF_PORT, 'Auto'), data=user_input)

        return self.async_show_form(
            step_id="user", data_schema=vol.Schema(fields), errors=errors
        ) 
开发者ID:doudz,项目名称:homeassistant-zigate,代码行数:20,代码来源:config_flow.py

示例8: MetricSchema

# 需要导入模块: import voluptuous [as 别名]
# 或者: from voluptuous import Schema [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:]) 
开发者ID:gnocchixyz,项目名称:gnocchi,代码行数:32,代码来源:api.py

示例9: OperationsSchema

# 需要导入模块: import voluptuous [as 别名]
# 或者: from voluptuous import Schema [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) 
开发者ID:gnocchixyz,项目名称:gnocchi,代码行数:13,代码来源:api.py

示例10: validate

# 需要导入模块: import voluptuous [as 别名]
# 或者: from voluptuous import Schema [as 别名]
def validate(schema, data, required=True):
    try:
        return voluptuous.Schema(schema, required=required)(data)
    except voluptuous.Invalid as e:
        abort(400, e) 
开发者ID:gnocchixyz,项目名称:gnocchi,代码行数:7,代码来源:api.py

示例11: BackwardCompatibleMeasuresList

# 需要导入模块: import voluptuous [as 别名]
# 或者: from voluptuous import Schema [as 别名]
def BackwardCompatibleMeasuresList(v):
        v = voluptuous.Schema(
            voluptuous.Any(MeasuresListSchema,
                           {voluptuous.Optional("archive_policy_name"):
                            six.text_type,
                            voluptuous.Optional("unit"):
                            six.text_type,
                            "measures": MeasuresListSchema}),
            required=True)(v)
        if isinstance(v, dict):
            return v
        else:
            # Old format
            return {"measures": v} 
开发者ID:gnocchixyz,项目名称:gnocchi,代码行数:16,代码来源:api.py

示例12: get_metric

# 需要导入模块: import voluptuous [as 别名]
# 或者: from voluptuous import Schema [as 别名]
def get_metric(self, metric=None, start=None, stop=None,
                   aggregation='mean', reaggregation=None, granularity=None,
                   needed_overlap=100.0, fill=None,
                   refresh=False, resample=None):
        if pecan.request.method == 'GET':
            try:
                metric_ids = voluptuous.Schema(
                    self.MetricIDsSchema, required=True)(arg_to_list(metric))
            except voluptuous.Error as e:
                abort(400, "Invalid input: %s" % e)
        else:
            self._workaround_pecan_issue_88()
            metric_ids = deserialize_and_validate(self.MetricIDsSchema)

        metric_ids = [six.text_type(m) for m in metric_ids]
        # Check RBAC policy
        metrics = pecan.request.indexer.list_metrics(
            attribute_filter={"in": {"id": metric_ids}})
        missing_metric_ids = (set(metric_ids)
                              - set(six.text_type(m.id) for m in metrics))
        if missing_metric_ids:
            # Return one of the missing one in the error
            abort(404, six.text_type(storage.MetricDoesNotExist(
                missing_metric_ids.pop())))
        return self.get_cross_metric_measures_from_objs(
            metrics, start, stop, aggregation, reaggregation,
            granularity, needed_overlap, fill, refresh, resample) 
开发者ID:gnocchixyz,项目名称:gnocchi,代码行数:29,代码来源:api.py

示例13: validate_openrc

# 需要导入模块: import voluptuous [as 别名]
# 或者: from voluptuous import Schema [as 别名]
def validate_openrc(openrc):
    openrc_schema = Schema({
        Required("auth_url"): str,
        Required("username"): str,
        Required("password"): str,
        Required("region_name"): str,
        Required("tenant_name"): str,
        Required("https_cacert"): str,
        Optional("https_insecure"): bool,
    })
    LOGGER.debug("Validating openrc config")
    openrc_schema(openrc) 
开发者ID:cisco-oss-eng,项目名称:Cloud99,代码行数:14,代码来源:schemas.py

示例14: validate_inventory

# 需要导入模块: import voluptuous [as 别名]
# 或者: from voluptuous import Schema [as 别名]
def validate_inventory(inventory):
    inventory_schema = Schema({
        Required("ip_or_hostname"): str,
        Required("username"): str,
        Required("password"): str,
        Required("role"): str,
    })
    LOGGER.debug("Validating inventory config")
    for host, config in inventory.items():
        inventory_schema(config) 
开发者ID:cisco-oss-eng,项目名称:Cloud99,代码行数:12,代码来源:schemas.py

示例15: async_step_user

# 需要导入模块: import voluptuous [as 别名]
# 或者: from voluptuous import Schema [as 别名]
def async_step_user(self, user_input=None):
        errors = {}
        if user_input is not None:
            if len(user_input['code']) != 4:
                errors["base"] = "not_hex"
            else:
                try:
                    if hex(int(user_input['code'], 16)).lower() != "0x" + user_input['code'].lower():
                        errors["base"] = "not_hex"
                except ValueError:
                    errors["base"] = "not_hex"
            if not errors:
                return self.async_create_entry(
                    title='duofern', data=user_input
                )
        if os.path.isdir("/dev/serial/by-id"):
            serialdevs = set(os.listdir("/dev/serial/by-id/"))
        else:
            serialdevs=["could not find /dev/serial/by-id/, did you plug in your dufoern stick correctly?"]
        return self.async_show_form(
            step_id='user',
            data_schema=vol.Schema({
                vol.Required('code'): str,
                vol.Optional('serial_port',
                             default="/dev/serial/by-id/usb-Rademacher_DuoFern_USB-Stick_WR04ZFP4-if00-port0"): vol.In(serialdevs),
                vol.Optional('config_file', default=os.path.join(os.path.dirname(__file__), "../../duofern.json")): str
            }),
            errors=errors
        ) 
开发者ID:gluap,项目名称:pyduofern,代码行数:31,代码来源:config_flow.py


注:本文中的voluptuous.Schema方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。