Python marshmallow.validate.Length() Examples

The following are 10 code examples of marshmallow.validate.Length(). 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 marshmallow.validate , or try the search function .
Example #1
Source File: custom_fields.py    From FlowKit with Mozilla Public License 2.0 7 votes vote down vote up
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,
        ) 
Example #2
Source File: convert.py    From lux with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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) 
Example #3
Source File: obj_list_obj.py    From polyaxon with Apache License 2.0 6 votes vote down vote up
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__
            )
        ) 
Example #4
Source File: test_marshmallow.py    From pydantic with MIT License 6 votes vote down vote up
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() 
Example #5
Source File: test_validation.py    From marshmallow-jsonschema with MIT License 5 votes vote down vote up
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) 
Example #6
Source File: params.py    From marshmallow-mongoengine with MIT License 5 votes vote down vote up
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)) 
Example #7
Source File: test_marshmallow_mongoengine.py    From marshmallow-mongoengine with MIT License 5 votes vote down vote up
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 
Example #8
Source File: custom_fields.py    From FlowKit with Mozilla Public License 2.0 5 votes vote down vote up
def __init__(self, **kwargs):
        super().__init__(
            fields.Float(validate=Range(min=-1.0, max=1.0)),
            validate=Length(equal=24),
            **kwargs,
        ) 
Example #9
Source File: dispatcher.py    From swagger-marshmallow-codegen with MIT License 5 votes vote down vote up
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 
Example #10
Source File: validate.py    From zimfarm with GNU General Public License v3.0 5 votes vote down vote up
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)