本文整理汇总了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)
示例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,
)
示例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__
)
)
示例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()
示例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)
示例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))
示例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
示例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
示例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)