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


Python validate.OneOf方法代码示例

本文整理汇总了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",
    } 
开发者ID:fuhrysteve,项目名称:marshmallow-jsonschema,代码行数:21,代码来源:test_dump.py

示例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) 
开发者ID:quantmind,项目名称:lux,代码行数:26,代码来源:convert.py

示例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,
        ) 
开发者ID:Flowminder,项目名称:FlowKit,代码行数:19,代码来源:custom_fields.py

示例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 
开发者ID:Flowminder,项目名称:FlowKit,代码行数:27,代码来源:joined_spatial_aggregate.py

示例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"] == [] 
开发者ID:fuhrysteve,项目名称:marshmallow-jsonschema,代码行数:13,代码来源:test_validation.py

示例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)
        ) 
开发者ID:apache,项目名称:airflow,代码行数:7,代码来源:enum_schemas.py

示例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)
        ) 
开发者ID:apache,项目名称:airflow,代码行数:7,代码来源:common_schema.py

示例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)] 
开发者ID:frol,项目名称:flask-restplus-server-example,代码行数:15,代码来源:parameters.py

示例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"])) 
开发者ID:sloria,项目名称:environs,代码行数:6,代码来源:test_environs.py

示例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)) 
开发者ID:touilleMan,项目名称:marshmallow-mongoengine,代码行数:7,代码来源:params.py

示例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') 
开发者ID:touilleMan,项目名称:marshmallow-mongoengine,代码行数:7,代码来源:test_marshmallow_mongoengine.py

示例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) 
开发者ID:Flowminder,项目名称:FlowKit,代码行数:5,代码来源:aggregation_unit.py

示例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 
开发者ID:podhmo,项目名称:swagger-marshmallow-codegen,代码行数:14,代码来源:dispatcher.py


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