How to use the marshmallow.fields 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 AllenInstitute / argschema / argschema / autodoc.py View on Github external
field_line += '(REQUIRED),'
                    else:
                        field_line += "NA,"

                    # add this field line to the documentation
                    try:
                        # get the set of types this field was derived from
                        if isinstance(field, mm.fields.List):
                            # if it's a list we want to do this for its container
                            base_types = inspect.getmro(type(field.container))
                        else:
                            base_types = inspect.getmro(type(field))

                        field_type = type(field)
                        # use these base_types to figure out the raw_json type for this field
                        if isinstance(field, mm.fields.Nested):
                            # if it's a nested field we should specify it as a dict, and link to the documentation
                            # for that nested schema
                            field_type = type(field.schema)
                            # schema_class_name = schema_type.__module__ + "." + schema_type.__name__
                            if field.many:
                                raw_type = 'list'
                            else:
                                raw_type = 'dict'
                        else:
                            # otherwise we should be able to look it up in the FIELD_TYPE_MAP
                            try:
                                base_type = next(
                                    bt for bt in base_types if bt in FIELD_TYPE_MAP)
                                raw_type = FIELD_TYPE_MAP[base_type].__name__
                                # hack in marshmallow for py3 which things Str is type 'bytes'
                                if raw_type == 'bytes':
github Netflix-Skunkworks / diffy / diffy_api / schemas.py View on Github external
incident_id = fields.String(required=True)
    target_plugin = fields.Nested(TargetPluginSchema, missing={})
    persistence_plugin = fields.Nested(PersistencePluginSchema, missing={})
    collection_plugin = fields.Nested(CollectionPluginSchema, missing={})
    payload_plugin = fields.Nested(PayloadPluginSchema, missing={})


class AnalysisSchema(BaselineSchema):
    analysis_plugin = fields.Nested(AnalysisPluginSchema, missing={})
    # TODO: move incident_id from BaselineSchema here


class TaskOutputSchema(DiffyOutputSchema):
    id = fields.String(attribute="id")
    created_at = fields.DateTime()
    args = fields.Dict()
    status = fields.String(attribute="status")


class TaskInputSchema(DiffyInputSchema):
    id = fields.String(required=True)


baseline_input_schema = BaselineSchema()
baseline_output_schema = BaselineSchema()
analysis_input_schema = AnalysisSchema()
analysis_output_schema = AnalysisSchema()
task_output_schema = TaskOutputSchema()
task_list_output_schema = TaskOutputSchema(many=True)
task_input_schema = TaskInputSchema()
github gatheringhallstudios / MHWorldData / mhdata / load / schema.py View on Github external
This module contains marshmallow schema definitions for loaded files.
Schemas in this file inherit from a BaseSchema, which is a schema object that supports grouping.
Those in the __groups__ dict are grouped together by prefix, and are usually used for localized dictionaries.
"""

from mhdata import cfg

from marshmallow import fields, ValidationError, validates, validates_schema
from .cfields import ValidatedStr, ExcelBool, BaseSchema, NestedPrefix

# schemas were added later down the line, so no schemas exist for certain objects yet
# schemas are used mostly for type conversion and pre-validation

class ItemSchema(BaseSchema):
    __groups__ = ('name', 'description')
    id = fields.Int()
    name = fields.Dict()
    description = fields.Dict()
    category = ValidatedStr("item", "material", "ammo", "misc", "hidden")
    subcategory = ValidatedStr(None, "account", "supply", "appraisal", "trade")
    rarity = fields.Int(allow_none=True, default=0)
    buy_price = fields.Int(allow_none=True)
    sell_price = fields.Int(allow_none=True)
    carry_limit = fields.Int(allow_none=True)
    points = fields.Int(allow_none=True)
    
    icon_name = fields.Str(allow_none=True)
    icon_color = ValidatedStr(None, *cfg.icon_colors)

class ItemCombinationSchema(BaseSchema):
    id = fields.Int()
    result = fields.Str()
github globality-corp / microcosm-flask / microcosm_flask / cloning.py View on Github external
"""
    Represents a DAG.

    Nodes should be overridden with a non-raw schema.

    """
    nodes = fields.Nested(
        fields.Raw,
        required=True,
        attribute="nodes_map",
    )
    edges = fields.List(
        fields.Nested(EdgeSchema),
        required=True,
    )
    substitutions = fields.List(
        fields.Nested(SubstitutionSchema),
        missing=[],
        required=False,
    )

    @pre_dump
    def unflatten(self, obj, **kwargs):
        """
        Translate substitutions dictionary into objects.

        """
        obj.substitutions = [
            dict(from_id=key, to_id=value)
            for key, value in getattr(obj, "substitutions", {}).items()
        ]
        return obj
github labd / commercetools-python-sdk / src / commercetools / schemas / _shopping_list.py View on Github external
)
    quantity = marshmallow.fields.Integer(allow_none=True)

    class Meta:
        unknown = marshmallow.EXCLUDE

    @marshmallow.post_load
    def post_load(self, data, **kwargs):
        del data["action"]
        return types.ShoppingListChangeTextLineItemQuantityAction(**data)


class ShoppingListChangeTextLineItemsOrderActionSchema(ShoppingListUpdateActionSchema):
    "Marshmallow schema for :class:`commercetools.types.ShoppingListChangeTextLineItemsOrderAction`."
    text_line_item_order = marshmallow.fields.List(
        marshmallow.fields.String(allow_none=True), data_key="textLineItemOrder"
    )

    class Meta:
        unknown = marshmallow.EXCLUDE

    @marshmallow.post_load
    def post_load(self, data, **kwargs):
        del data["action"]
        return types.ShoppingListChangeTextLineItemsOrderAction(**data)


class ShoppingListRemoveLineItemActionSchema(ShoppingListUpdateActionSchema):
    "Marshmallow schema for :class:`commercetools.types.ShoppingListRemoveLineItemAction`."
    line_item_id = marshmallow.fields.String(allow_none=True, data_key="lineItemId")
    quantity = marshmallow.fields.Integer(allow_none=True, missing=None)
github bcgov / queue-management / api / app / schemas / theq / service_req_schema.py View on Github external
class ServiceReqSchema(ma.ModelSchema):

    class Meta:
        model = ServiceReq
        jit = toastedmarshmallow.Jit

    citizen_id = fields.Int()
    channel_id = fields.Int()
    service_id = fields.Int()
    quantity = fields.Int()
    sr_number = fields.Int()
    periods = fields.Nested(PeriodSchema(exclude=('request_periods', 'reception_csr_ind', 'sr', 'sr_id', 'state_periods',)), many=True)
    sr_state = fields.Nested(SRStateSchema(exclude=('sr_state_id', 'sr_state_desc',)))
    service = fields.Nested(ServiceSchema(exclude=('actual_service_ind', 'deleted', 'display_dashboard_ind', 'prefix',
                                                   'service_code', 'service_desc', 'service_id',)))
    channel = fields.Nested(ChannelSchema(exclude=('channel_id',)))
    citizen = fields.Nested('CitizenSchema', exclude=('service_reqs',))
github Netflix / lemur / lemur / sources / schemas.py View on Github external
"""
.. module: lemur.sources.schemas
    :platform: unix
    :copyright: (c) 2018 by Netflix Inc., see AUTHORS for more
    :license: Apache, see LICENSE for more details.
.. moduleauthor:: Kevin Glisson 
"""
from marshmallow import fields, post_dump

from lemur.schemas import PluginInputSchema, PluginOutputSchema
from lemur.common.schema import LemurInputSchema, LemurOutputSchema


class SourceInputSchema(LemurInputSchema):
    id = fields.Integer()
    label = fields.String(required=True)
    description = fields.String()
    plugin = fields.Nested(PluginInputSchema)
    active = fields.Boolean()


class SourceOutputSchema(LemurOutputSchema):
    id = fields.Integer()
    label = fields.String()
    description = fields.String()
    plugin = fields.Nested(PluginOutputSchema)
    options = fields.List(fields.Dict())
    fields.Boolean()

    @post_dump
    def fill_object(self, data):
github polyaxon / polyaxon / polyaxon_schemas / ml / optimizers.py View on Github external
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function

from marshmallow import fields

from polyaxon_schemas.base import BaseConfig, BaseMultiSchema, BaseSchema


class BaseOptimizerSchema(BaseSchema):
    learning_rate = fields.Float(allow_none=True)
    decay_type = fields.Str(allow_none=True)
    decay_rate = fields.Float(allow_none=True)
    decay_steps = fields.Int(allow_none=True)
    start_decay_at = fields.Int(allow_none=True)
    stop_decay_at = fields.Int(allow_none=True)
    min_learning_rate = fields.Float(allow_none=True)
    staircase = fields.Bool(allow_none=True)
    global_step = fields.Str(allow_none=True)
    use_locking = fields.Bool(allow_none=True)
    name = fields.Str(allow_none=True)

    @staticmethod
    def schema_config():
        return BaseOptimizerConfig


class BaseOptimizerConfig(BaseConfig):
    REDUCED_ATTRIBUTES = ["name"]

    def __init__(
github polyaxon / polyaxon / polyaxon_schemas / ml / layers / recurrent.py View on Github external
stateful=False,
        unroll=False,
        implementation=0,
        **kwargs
    ):
        super(RecurrentConfig, self).__init__(**kwargs)
        self.return_sequences = return_sequences
        self.return_state = return_state
        self.go_backwards = go_backwards
        self.stateful = stateful
        self.unroll = unroll
        self.implementation = implementation


class SimpleRNNSchema(RecurrentSchema):
    units = fields.Int()
    activation = StrOrFct(allow_none=True, validate=validate.OneOf(ACTIVATION_VALUES))
    use_bias = fields.Bool(default=True, missing=True)
    kernel_initializer = fields.Nested(InitializerSchema, default=None, missing=None)
    recurrent_initializer = fields.Nested(InitializerSchema, default=None, missing=None)
    bias_initializer = fields.Nested(InitializerSchema, default=None, missing=None)
    kernel_regularizer = fields.Nested(RegularizerSchema, default=None, missing=None)
    recurrent_regularizer = fields.Nested(RegularizerSchema, default=None, missing=None)
    bias_regularizer = fields.Nested(RegularizerSchema, default=None, missing=None)
    activity_regularizer = fields.Nested(RegularizerSchema, default=None, missing=None)
    kernel_constraint = fields.Nested(ConstraintSchema, default=None, missing=None)
    recurrent_constraint = fields.Nested(ConstraintSchema, default=None, missing=None)
    bias_constraint = fields.Nested(ConstraintSchema, default=None, missing=None)
    dropout = fields.Float(default=0.0, missing=0.0)
    recurrent_dropout = fields.Float(default=0.0, missing=0.0)

    @staticmethod