Python marshmallow.validate.OneOf() Examples
The following are 19 code examples for showing how to use marshmallow.validate.OneOf(). These examples are extracted from open source projects. 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 check out the related API usage on the sidebar.
You may also want to check out all available functions/classes of the module
marshmallow.validate
, or try the search function
.
Example 1
Project: FlowKit Author: Flowminder File: custom_fields.py License: Mozilla Public License 2.0 | 7 votes |
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
Project: marshmallow-jsonschema Author: fuhrysteve File: test_dump.py License: MIT License | 6 votes |
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", }
Example 3
Project: lux Author: quantmind File: convert.py License: BSD 3-Clause "New" or "Revised" License | 6 votes |
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 4
Project: FlowKit Author: Flowminder File: joined_spatial_aggregate.py License: Mozilla Public License 2.0 | 6 votes |
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
Example 5
Project: marshmallow-jsonschema Author: fuhrysteve File: test_validation.py License: MIT License | 5 votes |
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"] == []
Example 6
Project: airflow Author: apache File: enum_schemas.py License: Apache License 2.0 | 5 votes |
def __init__(self, **metadata): super().__init__(**metadata) self.validators = ( [validate.OneOf(State.dag_states)] + list(self.validators) )
Example 7
Project: airflow Author: apache File: common_schema.py License: Apache License 2.0 | 5 votes |
def __init__(self, **metadata): super().__init__(**metadata) self.validators = ( [validate.OneOf(WeightRule.all_weight_rules())] + list(self.validators) )
Example 8
Project: flask-restplus-server-example Author: frol File: parameters.py License: MIT License | 5 votes |
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)]
Example 9
Project: environs Author: sloria File: test_environs.py License: MIT License | 5 votes |
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"]))
Example 10
Project: flask-restplus-patched Author: Jaza File: parameters.py License: MIT License | 5 votes |
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)]
Example 11
Project: marshmallow-mongoengine Author: touilleMan File: params.py License: MIT License | 5 votes |
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))
Example 12
Project: marshmallow-mongoengine Author: touilleMan File: test_marshmallow_mongoengine.py License: MIT License | 5 votes |
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')
Example 13
Project: FlowKit Author: Flowminder File: custom_fields.py License: Mozilla Public License 2.0 | 5 votes |
def __init__(self, required=False, **kwargs): validate = OneOf( ["second", "minute", "hour", "day", "month", "year"] ) # see total_network_objects.py super().__init__(required=required, validate=validate, **kwargs)
Example 14
Project: FlowKit Author: Flowminder File: custom_fields.py License: Mozilla Public License 2.0 | 5 votes |
def __init__(self, required=False, validate=None, **kwargs): if validate is not None: raise ValueError( "The AggregateBy field provides its own validation " "and thus does not accept a the 'validate' argument." ) validate = OneOf( ["second", "minute", "hour", "day", "month", "year", "century"] ) # see total_network_objects.py super().__init__(required=required, validate=validate, **kwargs)
Example 15
Project: FlowKit Author: Flowminder File: custom_fields.py License: Mozilla Public License 2.0 | 5 votes |
def __init__(self, required=True, validate=None, **kwargs): if validate is not None: raise ValueError( "The Statistic field provides its own validation " "and thus does not accept a the 'validate' argument." ) validate = OneOf( ["avg", "max", "min", "median", "mode", "stddev", "variance"] ) # see total_network_objects.py super().__init__(required=required, validate=validate, **kwargs)
Example 16
Project: FlowKit Author: Flowminder File: custom_fields.py License: Mozilla Public License 2.0 | 5 votes |
def __init__(self, required=False, allow_none=True, validate=None, **kwargs): if validate is not None: raise ValueError( "The SubscriberSubset field provides its own validation " "and thus does not accept a the 'validate' argument." ) super().__init__( required=required, allow_none=allow_none, validate=OneOf([None]), **kwargs )
Example 17
Project: FlowKit Author: Flowminder File: custom_fields.py License: Mozilla Public License 2.0 | 5 votes |
def __init__(self, required=True, validate=None, **kwargs): if validate is not None: raise ValueError( "The DFSMetric field provides its own validation and" "thus does not accept a the 'validate' argument." ) validate = OneOf(["amount", "commission", "fee", "discount"]) super().__init__(required=required, validate=validate, **kwargs)
Example 18
Project: FlowKit Author: Flowminder File: aggregation_unit.py License: Mozilla Public License 2.0 | 5 votes |
def __init__(self, required=True, **kwargs): validate = OneOf(["admin0", "admin1", "admin2", "admin3", "lon-lat"]) super().__init__(required=required, validate=validate, **kwargs)
Example 19
Project: swagger-marshmallow-codegen Author: podhmo File: dispatcher.py License: MIT License | 5 votes |
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