How to use the marshmallow.validate.OneOf function in marshmallow

To help you get started, we’ve selected a few marshmallow examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github plangrid / flask-rebar / tests / swagger_generation / test_marshmallow_to_swagger.py View on Github external
{"type": "array", "items": {"type": "integer"}, "minItems": 1},
            ),
            (
                m.fields.List(m.fields.Integer(), validate=v.Length(max=9)),
                {"type": "array", "items": {"type": "integer"}, "maxItems": 9},
            ),
            (
                m.fields.String(validate=v.Length(min=1)),
                {"type": "string", "minLength": 1},
            ),
            (
                m.fields.String(validate=v.Length(max=9)),
                {"type": "string", "maxLength": 9},
            ),
            (
                m.fields.String(validate=v.OneOf(["a", "b"])),
                {"type": "string", "enum": ["a", "b"]},
            ),
            (m.fields.Dict(), {"type": "object"}),
            (
                m.fields.Method(serialize="x", deserialize="y", swagger_type="integer"),
                {"type": "integer"},
            ),
            (
                m.fields.Function(
                    serialize=lambda _: _,
                    deserialize=lambda _: _,
                    swagger_type="string",
                ),
                {"type": "string"},
            ),
            (m.fields.Integer(validate=lambda value: True), {"type": "integer"}),
github marshmallow-code / apispec / tests / test_ext_marshmallow_field.py View on Github external
def test_field_with_choices_multiple(spec_fixture):
    field = fields.Str(
        validate=[
            validate.OneOf(["freddie", "brian", "john"]),
            validate.OneOf(["brian", "john", "roger"]),
        ]
    )
    res = spec_fixture.openapi.field2property(field)
    assert set(res["enum"]) == {"brian", "john"}
github fuhrysteve / marshmallow-jsonschema / tests / __init__.py View on Github external
updated = fields.DateTime()
    updated_local = fields.LocalDateTime(attribute="updated")
    species = fields.String(attribute="SPECIES")
    id = fields.String(default='no-id')
    homepage = fields.Url()
    email = fields.Email()
    balance = fields.Decimal()
    registered = fields.Boolean()
    hair_colors = fields.List(fields.Raw)
    sex_choices = fields.List(fields.Raw)
    finger_count = fields.Integer()
    uid = fields.UUID()
    time_registered = fields.Time()
    birthdate = fields.Date()
    since_created = fields.TimeDelta()
    sex = fields.Str(validate=validate.OneOf(
        choices=['male', 'female', 'non_binary', 'other'],
        labels=['Male', 'Female', 'Non-binary/fluid', 'Other']
    ))
    various_data = fields.Dict()
    addresses = fields.Nested(Address, many=True,
                              validate=validate.Length(min=1, max=3))
    github = fields.Nested(GithubProfile)
    const = fields.String(validate=validate.Length(equal=50))
github windprog / rest-utils / rest_utils / ma / convert.py View on Github external
def _add_column_kwargs(self, kwargs, column):
        """Add keyword arguments to kwargs (in-place) based on the passed in
        `Column `.
        """
        if not getattr(column, "foreign_keys", set()):
            # forgeign key不进行required校验, 使用errorhandler(StatementError)捕获错误处理
            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
        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, "python_type"):
            # set sqlachemy.DateTime default format
            python_type = column.type.python_type
            if python_type is datetime.datetime:
                # 这里处理datetime的默认参数
github frol / flask-restplus-server-example / flask_restplus_patched / parameters.py View on Github external
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)]
github Flowminder / FlowKit / flowmachine / flowmachine / core / server / query_schemas / custom_fields.py View on Github external
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
        )
github fossasia / open-event-server / app / api / schema / custom_forms.py View on Github external
"""
    API Schema for Custom Forms database model
    """
    class Meta:
        """
        Meta class for CustomForm Schema
        """
        type_ = 'custom-form'
        self_view = 'v1.custom_form_detail'
        self_view_kwargs = {'id': ''}
        inflect = dasherize

    id = fields.Integer(dump_only=True)
    field_identifier = fields.Str(required=True)
    form = fields.Str(required=True)
    type = fields.Str(default="text", validate=validate.OneOf(
        choices=["text", "checkbox", "select", "file", "image", "email",
                 "number"]))
    description = fields.Str(allow_none=True)
    is_required = fields.Boolean(default=False)
    is_included = fields.Boolean(default=False)
    is_complex = fields.Boolean(default=False)
    is_fixed = fields.Boolean(default=False)
    event = Relationship(attribute='event',
                         self_view='v1.custom_form_event',
                         self_view_kwargs={'id': ''},
                         related_view='v1.event_detail',
                         related_view_kwargs={'custom_form_id': ''},
                         schema='EventSchemaPublic',
                         type_='event')
github podhmo / swagger-marshmallow-codegen / examples / 02default / definition.py View on Github external
m1 = fields.Number(validate=[Range(min=100, max=None, min_inclusive=False, max_inclusive=True)])
    m2 = fields.Number(validate=[Range(min=100, max=None, min_inclusive=True, max_inclusive=True)])


class Regex_validation(Schema):
    team = fields.String(validate=[Regexp(regex=re.compile('team[1-9][0-9]+'))])
    team2 = fields.String(validate=[Length(min=None, max=10, equal=None), Regexp(regex=re.compile('team[1-9][0-9]+'))])


class Array_validation(Schema):
    nums = fields.List(fields.Integer(), validate=[ItemsRange(min=1, max=10, min_inclusive=True, max_inclusive=True), Unique()])


class Enum_validation(Schema):
    name = fields.String(required=True)
    money = fields.Integer(validate=[OneOf(choices=[1, 5, 10, 50, 100, 500, 1000, 5000, 10000], labels=[])])
    deposit = fields.Integer(validate=[MultipleOf(n=10000)])
    color = fields.String(required=True, validate=[OneOf(choices=['R', 'G', 'B'], labels=[])])
github Qiskit / qiskit-terra / qiskit / backends / models / jobstatus.py View on Github external
"""Model and schema for job status."""

from marshmallow.validate import OneOf

from qiskit.validation import BaseModel, BaseSchema, bind_schema
from qiskit.validation.fields import String


class JobStatusSchema(BaseSchema):
    """Schema for JobStatus."""

    # Required properties.
    job_id = String(required=True)
    status = String(required=True,
                    validate=OneOf(['DONE', 'QUEUED', 'CANCELLED', 'RUNNING', 'ERROR']))
    status_msg = String(required=True)


@bind_schema(JobStatusSchema)
class JobStatus(BaseModel):
    """Model for JobStatus.

    Please note that this class only describes the required fields. For the
    full description of the model, please check ``JobStatusSchema``.

    Attributes:
        job_id (str): backend job_id.
        status (str): status of the job.
        status_msg (str): status message.
    """
github hyperledger / aries-cloudagent-python / aries_cloudagent / messaging / valid.py View on Github external
class IndyCredRevId(Regexp):
    """Validate value against indy credential revocation identifier specification."""

    EXAMPLE = "12345"
    PATTERN = rf"^[1-9][0-9]*$"

    def __init__(self):
        """Initializer."""

        super().__init__(
            IndyCredRevId.PATTERN,
            error="Value {input} is not an indy credential revocation identifier",
        )


class IndyPredicate(OneOf):
    """Validate value against indy predicate."""

    EXAMPLE = ">="

    def __init__(self):
        """Initializer."""

        super().__init__(
            choices=["<", "<=", ">=", ">"],
            error="Value {input} must be one of {choices}",
        )


class IndyISO8601DateTime(Regexp):
    """Validate value against ISO 8601 datetime format, indy profile."""