How to use the marshmallow.validate 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 perdy / flama / tests / test_validation.py View on Github external
import datetime

import pytest
from marshmallow import Schema, fields, validate
from starlette.testclient import TestClient

from flama import exceptions
from flama.applications import Flama
from flama.validation import output_validation

utc = datetime.timezone.utc


class Product(Schema):
    name = fields.String(validate=validate.Length(max=10), required=True)
    rating = fields.Integer(missing=None, validate=validate.Range(min=0, max=100))
    created = fields.DateTime()


app = Flama()


@app.route("/product", methods=["GET"])
@output_validation()
def validate_product() -> Product:
    return {"name": "foo", "rating": 0, "created": datetime.datetime(2018, 1, 1, 0, 0, 0, tzinfo=datetime.timezone.utc)}


@app.route("/many-products", methods=["GET"])
@output_validation()
def validate_many_products() -> Product(many=True):
    return [
github fuhrysteve / marshmallow-jsonschema / tests / __init__.py View on Github external
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 marshmallow-code / marshmallow / tests / test_validate.py View on Github external
"http://info.example.com/?fred",
        "http://xn--mgbh0fb.xn--kgbechtv/",
        "http://example.com/blue/red%3Fand+green",
        "http://www.example.com/?array%5Bkey%5D=value",
        "http://xn--rsum-bpad.example.org/",
        "http://123.45.67.8/",
        "http://123.45.67.8:8329/",
        "http://[2001:db8::ff00:42]:8329",
        "http://[2001::1]:8329",
        "http://www.example.com:8000/foo",
        "http://user@example.com",
        "http://user:pass@example.com",
    ],
)
def test_url_absolute_valid(valid_url):
    validator = validate.URL(relative=False)
    assert validator(valid_url) == valid_url
github perdy / flama / tests / test_validation.py View on Github external
import datetime

import pytest
from marshmallow import Schema, fields, validate
from starlette.testclient import TestClient

from flama import exceptions
from flama.applications import Flama
from flama.validation import output_validation

utc = datetime.timezone.utc


class Product(Schema):
    name = fields.String(validate=validate.Length(max=10), required=True)
    rating = fields.Integer(missing=None, validate=validate.Range(min=0, max=100))
    created = fields.DateTime()


app = Flama()


@app.route("/product", methods=["GET"])
@output_validation()
def validate_product() -> Product:
    return {"name": "foo", "rating": 0, "created": datetime.datetime(2018, 1, 1, 0, 0, 0, tzinfo=datetime.timezone.utc)}


@app.route("/many-products", methods=["GET"])
@output_validation()
def validate_many_products() -> Product(many=True):
github hyperledger / aries-cloudagent-python / aries_cloudagent / protocols / issue_credential / v1_0 / routes.py View on Github external
)
    role = fields.Str(
        description="Role assigned in credential exchange",
        required=False,
        validate=validate.OneOf(
            [
                getattr(V10CredentialExchange, m)
                for m in vars(V10CredentialExchange)
                if m.startswith("ROLE_")
            ]
        ),
    )
    state = fields.Str(
        description="Credential exchange state",
        required=False,
        validate=validate.OneOf(
            [
                getattr(V10CredentialExchange, m)
                for m in vars(V10CredentialExchange)
                if m.startswith("STATE_")
            ]
        ),
    )


class V10CredentialExchangeListResultSchema(Schema):
    """Result schema for Aries#0036 v1.0 credential exchange query."""

    results = fields.List(
        fields.Nested(V10CredentialExchangeSchema),
        description="Aries#0036 v1.0 credential exchange records",
    )
github polyaxon / polyaxon / polyaxon_schemas / ops / tensorboard / op.py View on Github external
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function

from marshmallow import fields, validate

from polyaxon_schemas.ops.run import BaseRunConfig, BaseRunSchema


class TensorboardSchema(BaseRunSchema):
    kind = fields.Str(allow_none=True, validate=validate.Equal("tensorboard"))

    @staticmethod
    def schema_config():
        return TensorboardConfig


class TensorboardConfig(BaseRunConfig):
    IDENTIFIER = "tensorboard"
    SCHEMA = TensorboardSchema
github d0c-s4vage / lookatme / lookatme / schemas.py View on Github external
class TableSchema(Schema):
    header_divider = fields.Str(default="─")
    column_spacing = fields.Int(default=3)


class StyleSchema(Schema):
    """Styles schema for themes and style overrides within presentations
    """
    class Meta:
        render_module = YamlRender

    style = fields.Str(
        default="monokai",
        validate=validate.OneOf(list(pygments.styles.get_all_styles())),
    )

    title = fields.Nested(StyleFieldSchema, default={
        "fg": "#f30,bold,italics",
        "bg": "default",
    })
    author = fields.Nested(StyleFieldSchema, default={
        "fg": "#f30",
        "bg": "default",
    })
    date = fields.Nested(StyleFieldSchema, default={
        "fg": "#777",
        "bg": "default",
    })
    slides = fields.Nested(StyleFieldSchema, default={
        "fg": "#f30",
github hyperledger / aries-cloudagent-python / aries_cloudagent / protocols / present_proof / v1_0 / routes.py View on Github external
"""Parameters and validators for presentation exchange list query."""

    connection_id = fields.UUID(
        description="Connection identifier",
        required=False,
        example=UUIDFour.EXAMPLE,  # typically but not necessarily a UUID4
    )
    thread_id = fields.UUID(
        description="Thread identifier",
        required=False,
        example=UUIDFour.EXAMPLE,  # typically but not necessarily a UUID4
    )
    role = fields.Str(
        description="Role assigned in presentation exchange",
        required=False,
        validate=validate.OneOf(
            [
                getattr(V10PresentationExchange, m)
                for m in vars(V10PresentationExchange)
                if m.startswith("ROLE_")
            ]
        ),
    )
    state = fields.Str(
        description="Presentation exchange state",
        required=False,
        validate=validate.OneOf(
            [
                getattr(V10PresentationExchange, m)
                for m in vars(V10PresentationExchange)
                if m.startswith("STATE_")
            ]
github polyaxon / polyaxon / cli / polyaxon / schemas / polyflow / parallel / hyperband.py View on Github external
class ResourceConfig(BaseConfig, V1OptimizationResource):
    SCHEMA = ResourceSchema
    IDENTIFIER = "resource"

    def cast_value(self, value):
        if ResourceType.is_int(self.type):
            return int(value)
        if ResourceType.is_float(self.type):
            return float(value)
        return value


class HyperbandSchema(BaseSchema):
    kind = fields.Str(allow_none=True, validate=validate.Equal("hyperband"))
    matrix = fields.Dict(
        keys=fields.Str(), values=fields.Nested(MatrixSchema), allow_none=True
    )
    max_iter = RefOrObject(fields.Int(validate=validate.Range(min=1)))
    eta = RefOrObject(fields.Float(validate=validate.Range(min=0)))
    resource = fields.Nested(ResourceSchema)
    metric = fields.Nested(OptimizationMetricSchema)
    resume = RefOrObject(fields.Boolean(allow_none=True))
    seed = RefOrObject(fields.Int(allow_none=True))
    concurrency = fields.Int(allow_none=True)
    early_stopping = fields.Nested(EarlyStoppingSchema, many=True, allow_none=True)

    @staticmethod
    def schema_config():
        return HyperbandConfig
github podhmo / swagger-marshmallow-codegen / swagger_marshmallow_codegen / fields.py View on Github external
def __init__(self, pattern, nested_field, *args, **kwargs):
        fields.Field.__init__(self, *args, **kwargs)
        self.key_field = fields.Str(validate=validate.Regexp(pattern))
        self.nested_field = nested_field