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


Python validate.Length方法代码示例

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


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

示例1: _add_column_kwargs

# 需要导入模块: from marshmallow import validate [as 别名]
# 或者: from marshmallow.validate import Length [as 别名]
def _add_column_kwargs(self, kwargs, column):
        """Add keyword arguments to kwargs (in-place) based on the passed in
        `Column <sqlalchemy.schema.Column>`.
        """
        if column.nullable:
            kwargs['allow_none'] = True
        kwargs['required'] = not column.nullable and not _has_default(column)

        if hasattr(column.type, 'enums'):
            kwargs['validate'].append(validate.OneOf(choices=column.type.enums))

        # Add a length validator if a max length is set on the column
        # Skip UUID columns
        # (see https://github.com/marshmallow-code/marshmallow-sqlalchemy/issues/54)
        if hasattr(column.type, 'length'):
            try:
                python_type = column.type.python_type
            except (AttributeError, NotImplementedError):
                python_type = None
            if not python_type or not issubclass(python_type, uuid.UUID):
                kwargs['validate'].append(validate.Length(max=column.type.length))

        if hasattr(column.type, 'scale'):
            kwargs['places'] = getattr(column.type, 'scale', None) 
开发者ID:quantmind,项目名称:lux,代码行数:26,代码来源:convert.py

示例2: __init__

# 需要导入模块: from marshmallow import validate [as 别名]
# 或者: from marshmallow.validate import Length [as 别名]
def __init__(
        self, required=False, validate=None, allow_none=True, missing=None, **kwargs
    ):
        if validate is not None:
            raise ValueError(
                "The EventTypes field provides its own validation "
                "and thus does not accept a the 'validate' argument."
            )

        super().__init__(
            fields.String(validate=OneOf(["calls", "sms", "mds", "topups"])),
            required=required,
            validate=Length(min=1),
            allow_none=allow_none,
            missing=missing,
            **kwargs,
        ) 
开发者ID:Flowminder,项目名称:FlowKit,代码行数:19,代码来源:custom_fields.py

示例3: get_obj_or_list_obj

# 需要导入模块: from marshmallow import validate [as 别名]
# 或者: from marshmallow.validate import Length [as 别名]
def get_obj_or_list_obj(container, value, min_length=None, max_length=None):
    try:
        return container.deserialize(value)
    except (ValueError, TypeError, ValidationError):
        pass

    if not isinstance(value, (list, tuple)):
        raise ValidationError(
            "This field expects an {container} or a list of {container}s.".format(
                container=container.__class__.__name__
            )
        )

    value = validate.Length(min=min_length, max=max_length)(value)
    try:
        return [container.deserialize(v) for v in value]
    except (ValueError, TypeError):
        raise ValidationError(
            "This field expects an {container} or a list of {container}s.".format(
                container=container.__class__.__name__
            )
        ) 
开发者ID:polyaxon,项目名称:polyaxon,代码行数:24,代码来源:obj_list_obj.py

示例4: __init__

# 需要导入模块: from marshmallow import validate [as 别名]
# 或者: from marshmallow.validate import Length [as 别名]
def __init__(self, allow_extra):
        class LocationSchema(Schema):
            latitude = fields.Float(allow_none=True)
            longitude = fields.Float(allow_none=True)

        class SkillSchema(Schema):
            subject = fields.Str(required=True)
            subject_id = fields.Integer(required=True)
            category = fields.Str(required=True)
            qual_level = fields.Str(required=True)
            qual_level_id = fields.Integer(required=True)
            qual_level_ranking = fields.Float(default=0)

        class Model(Schema):
            id = fields.Integer(required=True)
            client_name = fields.Str(validate=validate.Length(max=255), required=True)
            sort_index = fields.Float(required=True)
            # client_email = fields.Email()
            client_phone = fields.Str(validate=validate.Length(max=255), allow_none=True)

            location = fields.Nested(LocationSchema)

            contractor = fields.Integer(validate=validate.Range(min=0), allow_none=True)
            upstream_http_referrer = fields.Str(validate=validate.Length(max=1023), allow_none=True)
            grecaptcha_response = fields.Str(validate=validate.Length(min=20, max=1000), required=True)
            last_updated = fields.DateTime(allow_none=True)
            skills = fields.Nested(SkillSchema, many=True)

        self.allow_extra = allow_extra  # unused
        self.schema = Model() 
开发者ID:samuelcolvin,项目名称:pydantic,代码行数:32,代码来源:test_marshmallow.py

示例5: test_length_validator_error

# 需要导入模块: from marshmallow import validate [as 别名]
# 或者: from marshmallow.validate import Length [as 别名]
def test_length_validator_error():
    class BadSchema(Schema):
        bob = fields.Integer(validate=validate.Length(min=1, max=3))

        class Meta:
            strict = True

    schema = BadSchema()
    json_schema = JSONSchema()

    with pytest.raises(UnsupportedValueError):
        json_schema.dump(schema) 
开发者ID:fuhrysteve,项目名称:marshmallow-jsonschema,代码行数:14,代码来源:test_validation.py

示例6: __init__

# 需要导入模块: from marshmallow import validate [as 别名]
# 或者: from marshmallow.validate import Length [as 别名]
def __init__(self, field_me):
        super(LenghtParam, self).__init__()
        # Add a length validator for max_length/min_length
        maxmin_args = {}
        if hasattr(field_me, 'max_length'):
            maxmin_args['max'] = field_me.max_length
        if hasattr(field_me, 'min_length'):
            maxmin_args['min'] = field_me.min_length
        self.field_kwargs['validate'].append(validate.Length(**maxmin_args)) 
开发者ID:touilleMan,项目名称:marshmallow-mongoengine,代码行数:11,代码来源:params.py

示例7: test_length_validator_set

# 需要导入模块: from marshmallow import validate [as 别名]
# 或者: from marshmallow.validate import Length [as 别名]
def test_length_validator_set(self, models):
        fields_ = fields_for_model(models.Student)
        validator = contains_validator(fields_['full_name'], validate.Length)
        assert validator
        assert validator.max == 255
        validator = contains_validator(fields_['email'], validate.Length)
        assert validator
        assert validator.max == 100
        validator = contains_validator(fields_['profile_uri'], validate.Length)
        assert validator
        assert validator.max == 200
        validator = contains_validator(fields_['age'], validate.Range)
        assert validator
        assert validator.max == 99
        assert validator.min == 10 
开发者ID:touilleMan,项目名称:marshmallow-mongoengine,代码行数:17,代码来源:test_marshmallow_mongoengine.py

示例8: dispatch_validator

# 需要导入模块: from marshmallow import validate [as 别名]
# 或者: from marshmallow.validate import Length [as 别名]
def dispatch_validator(self, c, value):
        from marshmallow.validate import Length, Regexp, OneOf
        from .validate import Range, MultipleOf, Unique, ItemsRange

        if isinstance(value, (Regexp)):
            c.import_("re")  # xxx
            c.from_("marshmallow.validate", value.__class__.__name__)
        elif isinstance(value, (Length, OneOf)):
            c.from_("marshmallow.validate", value.__class__.__name__)
        elif isinstance(value, (Range, MultipleOf, Unique, ItemsRange)):
            c.from_("swagger_marshmallow_codegen.validate", value.__class__.__name__)
        return value 
开发者ID:podhmo,项目名称:swagger-marshmallow-codegen,代码行数:14,代码来源:dispatcher.py

示例9: ssh_key

# 需要导入模块: from marshmallow import validate [as 别名]
# 或者: from marshmallow.validate import Length [as 别名]
def ssh_key():
    """
    Validate ssh public keys exists and matches with username
    """

    # validate request json
    class KeySchema(Schema):
        username = fields.String(required=True, validate=validate.Length(min=1))
        key = fields.String(required=True, validate=validate.Length(min=1))

    try:
        request_json = KeySchema().load(request.get_json())
    except ValidationError as e:
        raise errors.InvalidRequestJSON(e.messages)

    # compute fingerprint
    try:
        key = request_json["key"]
        rsa_key = paramiko.RSAKey(data=base64.b64decode(key))
        fingerprint = binascii.hexlify(rsa_key.get_fingerprint()).decode()
    except (binascii.Error, paramiko.SSHException):
        raise errors.BadRequest("Invalid RSA key")

    # database
    username = request_json["username"]
    user = Users().update_one(
        {
            "username": username,
            "ssh_keys": {"$elemMatch": {"fingerprint": fingerprint}},
        },
        {"$set": {"ssh_keys.$.last_used": datetime.now()}},
    )

    if user.matched_count == 0:
        raise errors.Unauthorized()
    return Response(status=HTTPStatus.NO_CONTENT) 
开发者ID:openzim,项目名称:zimfarm,代码行数:38,代码来源:validate.py


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