How to use the marshmallow.fields.Field 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 marshmallow-code / marshmallow / tests / test_schema.py View on Github external
def test_invalid_type_passed_to_nested_field(self):
        class InnerSchema(Schema):
            foo = fields.Field()

        class MySchema(Schema):
            inner = fields.Nested(InnerSchema, many=True)

        sch = MySchema()

        sch.load({"inner": [{"foo": 42}]})

        with pytest.raises(ValidationError) as excinfo:
            sch.load({"inner": "invalid"})
        errors = excinfo.value.messages
        assert "inner" in errors
        assert errors["inner"] == ["Invalid type."]

        class OuterSchema(Schema):
            inner = fields.Nested(InnerSchema)
github podhmo / swagger-marshmallow-codegen / examples / 04github / githubschema.py View on Github external
class PullsCommentsItem_linksHtml(Schema):
    href = fields.String()


class PullsPost(Schema):
    base = fields.String()
    body = fields.String()
    head = fields.String()
    title = fields.String()


class PutSubscription(Schema):
    created_at = fields.String()
    ignored = fields.Boolean()
    reason = fields.Field()
    subscribed = fields.Boolean()
    thread_url = fields.String()
    url = fields.String()


class Rate_limit(Schema):
    rate = fields.Nested('Rate_limitRate')


class Rate_limitRate(Schema):
    limit = fields.Integer()
    remaining = fields.Integer()
    reset = fields.Integer()


class Readme(Schema):
github facultyai / faculty / faculty / clients / experiment / _schemas.py View on Github external
ExperimentRunStatus,
    ListExperimentRunsResponse,
    LogicalOperator,
    Metric,
    MetricDataPoint,
    MetricHistory,
    Page,
    Pagination,
    Param,
    RestoreExperimentRunsResponse,
    SortOrder,
    Tag,
)


class _OptionalField(fields.Field):
    """Wrap another field, passing through Nones."""

    def __init__(self, nested, *args, **kwargs):
        self.nested = nested
        super(_OptionalField, self).__init__(*args, **kwargs)

    def _deserialize(self, value, *args, **kwargs):
        if value is None:
            return None
        else:
            return self.nested._deserialize(value, *args, **kwargs)

    def _serialize(self, value, *args, **kwargs):
        if value is None:
            return None
        else:
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
github rotki / rotki / rotkehlchen / api / v1 / encoding.py View on Github external
def _deserialize(
            self,
            value: str,
            attr: Optional[str],  # pylint: disable=unused-argument
            data: Optional[Mapping[str, Any]],  # pylint: disable=unused-argument
            **_kwargs: Any,
    ) -> Timestamp:
        try:
            timestamp = deserialize_timestamp(value)
        except DeserializationError as e:
            raise ValidationError(str(e))

        return timestamp


class ColorField(fields.Field):

    def _deserialize(
            self,
            value: str,
            attr: Optional[str],  # pylint: disable=unused-argument
            data: Optional[Mapping[str, Any]],  # pylint: disable=unused-argument
            **_kwargs: Any,
    ) -> HexColorCode:
        try:
            color_code = deserialize_hex_color_code(value)
        except DeserializationError as e:
            raise ValidationError(str(e))

        return color_code
github raiden-network / raiden / raiden / api / v1 / encoding.py View on Github external
if not is_checksum_address(value):
            self.fail("invalid_checksum")

        try:
            value = to_canonical_address(value)
        except ValueError:
            self.fail("invalid_data")

        if len(value) != 20:
            self.fail("invalid_size")

        return value


class DataField(fields.Field):
    @staticmethod
    def _serialize(value, attr, obj):  # pylint: disable=unused-argument
        return data_encoder(value)

    @staticmethod
    def _deserialize(value, attr, data):  # pylint: disable=unused-argument
        return data_decoder(value)


class BaseOpts(SchemaOpts):
    """
    This allows for having the Object the Schema encodes to inside of the class Meta
    """

    def __init__(self, meta):
        SchemaOpts.__init__(self, meta)
github windprog / rest-utils / rest_utils / ma / convert.py View on Github external
SQLA_TYPE_MAPPING = {
        sa.Enum: fields.Field,

        postgresql.BIT: fields.Integer,
        postgresql.UUID: fields.UUID,
        postgresql.MACADDR: fields.String,
        postgresql.INET: fields.String,
        postgresql.JSON: fields.Raw,
        postgresql.JSONB: fields.Raw,
        postgresql.HSTORE: fields.Raw,
        postgresql.ARRAY: _postgres_array_factory,

        mysql.BIT: fields.Integer,
        mysql.YEAR: fields.Integer,
        mysql.SET: fields.List,
        mysql.ENUM: fields.Field,

        mssql.BIT: fields.Integer,
    }
    if hasattr(sa, 'JSON'):
        SQLA_TYPE_MAPPING[sa.JSON] = fields.Raw

    def __init__(self, schema_cls=None):
        self.schema_cls = schema_cls

    @property
    def type_mapping(self):
        if self.schema_cls:
            return self.schema_cls.TYPE_MAPPING
        else:
            return ma.Schema.TYPE_MAPPING
github compute-tooling / compute-studio / workers / cs_workers / services / scheduler.py View on Github external
CS_URL = os.environ.get("CS_URL")
PROJECT = os.environ.get("PROJECT")

redis_conn = dict(
    username="scheduler",
    password=os.environ.get("REDIS_SCHEDULER_PW"),
    **redis_conn_from_env(),
)


class Payload(ma.Schema):
    task_id = ma.fields.UUID(required=False)
    task_name = ma.fields.Str(required=True)
    task_kwargs = ma.fields.Dict(
        keys=ma.fields.Str(), values=ma.fields.Field(), missing=dict
    )
    tag = ma.fields.Str(required=False, allow_none=True)


class Scheduler(tornado.web.RequestHandler):
    def initialize(self, config=None, rclient=None):
        self.config = config
        self.rclient = rclient

    async def post(self, owner, title):
        print("POST -- /", owner, title)
        if not self.request.body:
            return
        payload = Payload().loads(self.request.body.decode("utf-8"))
        print("payload", payload)
        if f"{owner}/{title}" not in self.config.projects():
github cosven / feeluown-core / fuocore / schemas.py View on Github external
# -*- coding: utf-8 -*-

from marshmallow import Schema, fields, post_load

from fuocore.models import (
    AlbumModel,
    ArtistModel,
    PlaylistModel,
    SongModel,
    UserModel,
)


class BaseSchema(Schema):
    identifier = fields.Field(required=True)
    source = fields.Str(required=True)
    desc = fields.Str()


class ArtistSchema(BaseSchema):
    # TODO: 添加一个 alias 字段?
    name = fields.Str(required=True)
    cover = fields.Str()  # NOTE: 可能需要单独一个 Schema
    songs = fields.List(fields.Nested('SongSchema'))

    @post_load
    def create_model(self, data):
        return ArtistModel(**data)


class AlbumSchema(BaseSchema):
github PrefectHQ / prefect / src / prefect / utilities / serialization.py View on Github external
class OneOfSchema(marshmallow_oneofschema.OneOfSchema):
    """
    A subclass of marshmallow_oneofschema.OneOfSchema that can load DotDicts
    """

    class Meta:
        unknown = EXCLUDE

    def _load(self, data, partial=None, unknown=None):  # type: ignore
        if isinstance(data, DotDict):
            data = as_nested_dict(data, dict)
        return super()._load(data=data, partial=partial, unknown=unknown)


class Bytes(fields.Field):
    """
    A Marshmallow Field that serializes bytes to a base64-encoded string, and deserializes
    a base64-encoded string to bytes.

    Args:
        - *args (Any): the arguments accepted by `marshmallow.Field`
        - **kwargs (Any): the keyword arguments accepted by `marshmallow.Field`
    """

    def __init__(self, *args: Any, **kwargs: Any) -> None:
        super().__init__(*args, **kwargs)

    def _serialize(self, value, attr, obj, **kwargs):  # type: ignore
        if value is not None:
            return base64.b64encode(value).decode("utf-8")