本文整理汇总了Python中marshmallow.validate.OneOf方法的典型用法代码示例。如果您正苦于以下问题:Python validate.OneOf方法的具体用法?Python validate.OneOf怎么用?Python validate.OneOf使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类marshmallow.validate
的用法示例。
在下文中一共展示了validate.OneOf方法的13个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_dumps_iterable_enums
# 需要导入模块: from marshmallow import validate [as 别名]
# 或者: from marshmallow.validate import OneOf [as 别名]
def test_dumps_iterable_enums():
mapping = {"a": 0, "b": 1, "c": 2}
class TestSchema(Schema):
foo = fields.Integer(
validate=validate.OneOf(mapping.values(), labels=mapping.keys())
)
schema = TestSchema()
dumped = validate_and_dump(schema)
assert dumped["definitions"]["TestSchema"]["properties"]["foo"] == {
"enum": [v for v in mapping.values()],
"enumNames": [k for k in mapping.keys()],
"format": "integer",
"title": "foo",
"type": "number",
}
示例2: _add_column_kwargs
# 需要导入模块: from marshmallow import validate [as 别名]
# 或者: from marshmallow.validate import OneOf [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)
示例3: __init__
# 需要导入模块: from marshmallow import validate [as 别名]
# 或者: from marshmallow.validate import OneOf [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,
)
示例4: validate_method
# 需要导入模块: from marshmallow import validate [as 别名]
# 或者: from marshmallow.validate import OneOf [as 别名]
def validate_method(self, data, **kwargs):
continuous_metrics = [
"radius_of_gyration",
"unique_location_counts",
"topup_balance",
"subscriber_degree",
"topup_amount",
"event_count",
"nocturnal_events",
"pareto_interactions",
"displacement",
]
categorical_metrics = ["handset"]
if data["metric"]["query_kind"] in continuous_metrics:
validate = OneOf(
["avg", "max", "min", "median", "mode", "stddev", "variance"]
)
elif data["metric"]["query_kind"] in categorical_metrics:
validate = OneOf(["distr"])
else:
raise ValidationError(
f"{data['metric']['query_kind']} does not have a valid metric type."
)
validate(data["method"])
return data
示例5: test_one_of_empty_enum
# 需要导入模块: from marshmallow import validate [as 别名]
# 或者: from marshmallow.validate import OneOf [as 别名]
def test_one_of_empty_enum():
class TestSchema(Schema):
foo = fields.String(validate=OneOf([]))
schema = TestSchema()
dumped = validate_and_dump(schema)
foo_property = dumped["definitions"]["TestSchema"]["properties"]["foo"]
assert foo_property["enum"] == []
assert foo_property["enumNames"] == []
示例6: __init__
# 需要导入模块: from marshmallow import validate [as 别名]
# 或者: from marshmallow.validate import OneOf [as 别名]
def __init__(self, **metadata):
super().__init__(**metadata)
self.validators = (
[validate.OneOf(State.dag_states)] + list(self.validators)
)
示例7: __init__
# 需要导入模块: from marshmallow import validate [as 别名]
# 或者: from marshmallow.validate import OneOf [as 别名]
def __init__(self, **metadata):
super().__init__(**metadata)
self.validators = (
[validate.OneOf(WeightRule.all_weight_rules())] + list(self.validators)
)
示例8: __init__
# 需要导入模块: from marshmallow import validate [as 别名]
# 或者: from marshmallow.validate import OneOf [as 别名]
def __init__(self, *args, **kwargs):
if 'many' in kwargs:
assert kwargs['many'], "PATCH Parameters must be marked as 'many'"
kwargs['many'] = True
super(PatchJSONParameters, self).__init__(*args, **kwargs)
if not self.PATH_CHOICES:
raise ValueError("%s.PATH_CHOICES has to be set" % self.__class__.__name__)
# Make a copy of `validators` as otherwise we will modify the behaviour
# of all `marshmallow.Schema`-based classes
self.fields['op'].validators = \
self.fields['op'].validators + [validate.OneOf(self.OPERATION_CHOICES)]
self.fields['path'].validators = \
self.fields['path'].validators + [validate.OneOf(self.PATH_CHOICES)]
示例9: test_can_add_marshmallow_validator
# 需要导入模块: from marshmallow import validate [as 别名]
# 或者: from marshmallow.validate import OneOf [as 别名]
def test_can_add_marshmallow_validator(self, set_env, env):
set_env({"NODE_ENV": "invalid"})
with pytest.raises(environs.EnvError):
env("NODE_ENV", validate=validate.OneOf(["development", "production"]))
示例10: __init__
# 需要导入模块: from marshmallow import validate [as 别名]
# 或者: from marshmallow.validate import OneOf [as 别名]
def __init__(self, field_me):
super(ChoiceParam, self).__init__()
choices = getattr(field_me, 'choices', None)
if choices:
self.field_kwargs['validate'].append(validate.OneOf(choices))
示例11: test_sets_enum_choices
# 需要导入模块: from marshmallow import validate [as 别名]
# 或者: from marshmallow.validate import OneOf [as 别名]
def test_sets_enum_choices(self, models):
fields_ = fields_for_model(models.Course)
validator = contains_validator(fields_['level'], validate.OneOf)
assert validator
assert validator.choices == ('Primary', 'Secondary')
示例12: __init__
# 需要导入模块: from marshmallow import validate [as 别名]
# 或者: from marshmallow.validate import OneOf [as 别名]
def __init__(self, required=True, **kwargs):
validate = OneOf(["admin0", "admin1", "admin2", "admin3", "lon-lat"])
super().__init__(required=required, validate=validate, **kwargs)
示例13: dispatch_validator
# 需要导入模块: from marshmallow import validate [as 别名]
# 或者: from marshmallow.validate import OneOf [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