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


Python voluptuous.Invalid方法代码示例

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


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

示例1: get_pagination_options

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

示例2: post

# 需要导入模块: import voluptuous [as 别名]
# 或者: from voluptuous import Invalid [as 别名]
def post(self):
        schema = pecan.request.indexer.get_resource_type_schema()
        body = deserialize_and_validate(schema)
        body["state"] = "creating"

        try:
            rt = schema.resource_type_from_dict(**body)
        except resource_type.InvalidResourceAttribute as e:
            abort(400, "Invalid input: %s" % e)

        enforce("create resource type", body)
        try:
            rt = pecan.request.indexer.create_resource_type(rt)
        except indexer.ResourceTypeAlreadyExists as e:
            abort(409, six.text_type(e))
        set_resp_location_hdr("/resource_type/" + rt.name)
        pecan.response.status = 201
        return rt 
开发者ID:gnocchixyz,项目名称:gnocchi,代码行数:20,代码来源:api.py

示例3: Alphanumeric

# 需要导入模块: import voluptuous [as 别名]
# 或者: from voluptuous import Invalid [as 别名]
def Alphanumeric(msg=None):
    '''
    Checks whether a value is:
        - int, or
        - long, or
        - float without a fractional part, or
        - str or unicode composed only of alphanumeric characters
    '''
    def fn(value):
        if not any([
            isinstance(value, numbers.Integral),
            (isinstance(value, float) and value.is_integer()),
            (isinstance(value, basestring) and value.isalnum())
        ]):
            raise Invalid(msg or (
                'Invalid input <{0}>; expected an integer'.format(value))
            )
        else:
            return value
    return fn 
开发者ID:manjitkumar,项目名称:drf-url-filters,代码行数:22,代码来源:validations.py

示例4: StrictlyAlphanumeric

# 需要导入模块: import voluptuous [as 别名]
# 或者: from voluptuous import Invalid [as 别名]
def StrictlyAlphanumeric(msg=None):
    '''
    Checks whether a value is:
        - str or unicode, and
        - composed of both alphabets and digits
    '''
    def fn(value):
        if not (
            isinstance(value, basestring) and
            value.isalnum() and not
            value.isdigit() and not
            value.isalpha()
        ):
            raise Invalid(msg or (
                'Invalid input <{0}>; expected an integer'.format(value))
            )
        else:
            return value
    return fn 
开发者ID:manjitkumar,项目名称:drf-url-filters,代码行数:21,代码来源:validations.py

示例5: __call__

# 需要导入模块: import voluptuous [as 别名]
# 或者: from voluptuous import Invalid [as 别名]
def __call__(self, value):
        '''
        Checks whether a value is list of given validation_function.
        Returns list of validated values or just one valid value in
        list if there is only one element in given CSV string.
        '''
        try:
            if isinstance(value, basestring):
                if self.separator in value:
                    seperated_string_values =[item.strip() for item
                        in value.split(self.separator)]
                    values = [self.validation_function(item) for item
                        in seperated_string_values]
                else:
                    values = [self.validation_function(value)]
                return values
            else:
                raise ValueError
        except (Invalid, ValueError) as e:
            raise Invalid(self.msg or
                ('<{0}> is not valid set of <{1}>, {2}'.format(
                    value,
                    self.value_type,
                        e))) 
开发者ID:manjitkumar,项目名称:drf-url-filters,代码行数:26,代码来源:validations.py

示例6: post

# 需要导入模块: import voluptuous [as 别名]
# 或者: from voluptuous import Invalid [as 别名]
def post(self):

        try:
            body = json.loads(self.request.body)
            web_service_model.banana_model(body)
            type_table = self._monanas.compute_type_table(body["content"])
            self.write(type_table)
        except (AttributeError, voluptuous.Invalid, ValueError) as e:
            logger.warn("Wrong request: {}.".
                        format(e))
            self.set_status(400, "The request body was malformed.")
        except Exception as e:
            tb = traceback.format_exc()
            print(tb)
            logger.error("Unexpected error: {}. {}".
                         format(sys.exc_info()[0], e))
            self.set_status(500, "Internal server error.")

        self.flush()
        self.finish() 
开发者ID:openstack,项目名称:monasca-analytics,代码行数:22,代码来源:request_handler.py

示例7: validate_links

# 需要导入模块: import voluptuous [as 别名]
# 或者: from voluptuous import Invalid [as 别名]
def validate_links(links):
    """Validate links to make sure, nothing is missing

    :type links: dict
    :param links: connection links to validate
    :raises: SchemaError -- if any link is missing
    """
    missing = set([])
    all_keys = set(links.keys())
    for connections in links.values():
        for component in connections:
            if component not in all_keys:
                missing.add(component.id())
    if len(missing) > 0:
        raise voluptuous.Invalid([
            "In connections section, the following components are not "
            "connected\n\t{}\n"
            "please modify the configuration so that their list of "
            "connections is at least '[]'".format(", ".join(missing))], []) 
开发者ID:openstack,项目名称:monasca-analytics,代码行数:21,代码来源:validation.py

示例8: _validate_existing_id

# 需要导入模块: import voluptuous [as 别名]
# 或者: from voluptuous import Invalid [as 别名]
def _validate_existing_id(config, component_id):
    """Check that the id passed as parameter is defined in the configuration

    :type config: dict
    :param config: configuration model for the whole system
    :type component_id: str
    :param component_id: component ID to be found in configuration
    """
    found_id = False
    for comp_type in valid_connection_types.keys():
        if component_id in config[comp_type].keys():
            found_id = True
    if not found_id:
        raise voluptuous.Invalid([
            'In "connections", component `{}` hasn\'t been defined'
            .format(component_id)
        ], []) 
开发者ID:openstack,项目名称:monasca-analytics,代码行数:19,代码来源:validation.py

示例9: boolean

# 需要导入模块: import voluptuous [as 别名]
# 或者: from voluptuous import Invalid [as 别名]
def boolean(value):
    '''
    Convert the content of a string (or a number) to a boolean.
    Do nothing when input value is already a boolean.

    This filter accepts usual values for ``True`` and ``False``:
    "0", "f", "false", "n", etc.
    '''
    if value is None or isinstance(value, bool):
        return value

    try:
        return bool(int(value))
    except ValueError:
        lower_value = value.strip().lower()
        if not lower_value:
            return None
        if lower_value in ('f', 'false', 'n', 'no', 'off'):
            return False
        if lower_value in ('on', 't', 'true', 'y', 'yes'):
            return True
        raise Invalid('Unable to parse boolean {0}'.format(value)) 
开发者ID:opendatateam,项目名称:udata,代码行数:24,代码来源:filters.py

示例10: test_boolean

# 需要导入模块: import voluptuous [as 别名]
# 或者: from voluptuous import Invalid [as 别名]
def test_boolean(self):
        true_values = ('1', 'on', 't', 'TRUE', 'true', 'y', 'yes', '  1  ',
                       '  tRuE  ', True, 1, 2, -1)
        false_values = ('0', 'f', 'FALSE', 'false', 'n', 'no', 'off', '  0  ',
                        '  f  ', False, 0)
        none_values = ('', '   ', None)

        for value in true_values:
            assert filters.boolean(value)

        for value in false_values:
            assert filters.boolean(value) is False

        for value in none_values:
            assert filters.boolean(value) is None

        with pytest.raises(Invalid):
            filters.boolean('vrai') 
开发者ID:opendatateam,项目名称:udata,代码行数:20,代码来源:test_filters.py

示例11: _check_GitHubTeam_format

# 需要导入模块: import voluptuous [as 别名]
# 或者: from voluptuous import Invalid [as 别名]
def _check_GitHubTeam_format(value):
    if not value:
        raise voluptuous.Invalid("A GitHub team cannot be an empty string")

    # Remove leading @ if any:
    # This format is accepted in conditions so we're happy to accept it here too.
    if value[0] == "@":
        value = value[1:]

    org, sep, team = value.partition("/")

    if sep == "" and team == "":
        # Just a slug
        return _check_GitHubLogin_format(org, "team")

    _check_GitHubLogin_format(org, "organization")
    return _check_GitHubLogin_format(team, "team") 
开发者ID:Mergifyio,项目名称:mergify-engine,代码行数:19,代码来源:types.py

示例12: schema_ext

# 需要导入模块: import voluptuous [as 别名]
# 或者: from voluptuous import Invalid [as 别名]
def schema_ext(value):
        try:
            return utils.UUID(value)
        except ValueError as e:
            raise voluptuous.Invalid(e) 
开发者ID:gnocchixyz,项目名称:gnocchi,代码行数:7,代码来源:resource_type.py

示例13: MetricSchema

# 需要导入模块: import voluptuous [as 别名]
# 或者: from voluptuous import Invalid [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

示例14: OperationsSchema

# 需要导入模块: import voluptuous [as 别名]
# 或者: from voluptuous import Invalid [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

示例15: abort

# 需要导入模块: import voluptuous [as 别名]
# 或者: from voluptuous import Invalid [as 别名]
def abort(status_code, detail=''):
    """Like pecan.abort, but make sure detail is a string."""
    if status_code == 404 and not detail:
        raise RuntimeError("http code 404 must have 'detail' set")

    if isinstance(detail, voluptuous.Invalid):
        detail = {
            'cause': 'Invalid input',
            'reason': six.text_type(detail),
            'detail': [six.text_type(path) for path in detail.path],
        }
    elif isinstance(detail, Exception):
        detail = detail.jsonify()
    LOG.debug("Aborting request. Code [%s]. Details [%s]", status_code, detail)
    return pecan.abort(status_code, detail) 
开发者ID:gnocchixyz,项目名称:gnocchi,代码行数:17,代码来源:api.py


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