argschema.fields package

Submodules

argschema.fields.files module

marshmallow fields related to validating input and output file paths

class argschema.fields.files.InputDir(default=<marshmallow.missing>, attribute=None, load_from=None, dump_to=None, error=None, validate=None, required=False, allow_none=None, load_only=False, dump_only=False, missing=<marshmallow.missing>, error_messages=None, **metadata)

Bases: marshmallow.fields.String

InputDir is marshmallow.fields.Str subclass which is a path to a a directory that exists and that the user can access (presently checked with os.access)

class argschema.fields.files.InputFile(default=<marshmallow.missing>, attribute=None, load_from=None, dump_to=None, error=None, validate=None, required=False, allow_none=None, load_only=False, dump_only=False, missing=<marshmallow.missing>, error_messages=None, **metadata)

Bases: marshmallow.fields.String

InputDile is a marshmallow.fields.Str subclass which is a path to a file location which can be read by the user (presently passes os.path.isfile and os.access = R_OK)

class argschema.fields.files.OutputDir(mode=None, *args, **kwargs)

Bases: marshmallow.fields.String

OutputDir is a marshmallow.fields.Str subclass which is a path to a location where this module will write files. Validation will check that the directory exists and create the directory if it is not present, and will fail validation if the directory cannot be created or cannot be written to.

Parameters:
  • mode (str) – mode to create directory
  • *args – smae as passed to marshmallow.fields.Str
  • **kwargs – same as passed to marshmallow.fields.Str
class argschema.fields.files.OutputFile(default=<marshmallow.missing>, attribute=None, load_from=None, dump_to=None, error=None, validate=None, required=False, allow_none=None, load_only=False, dump_only=False, missing=<marshmallow.missing>, error_messages=None, **metadata)

Bases: marshmallow.fields.String

OutputFile marshmallow.fields.Str subclass which is a path to a
file location that can be written to by the current user (presently tested by opening a temporary file to that location)
argschema.fields.files.validate_input_path(value)
argschema.fields.files.validate_outpath(path)

argschema.fields.loglevel module

marshmallow fields related to setting logging levels

class argschema.fields.loglevel.LogLevel(**kwargs)

Bases: marshmallow.fields.String

LogLevel is a field type that provides a setting for the loglevel of python.logging. This class will both validate the input and also set the input globally. In simple scenarios, a module will not have to do any manipulation of loglevel.

options = ['FATAL', 'CRITICAL', 'ERROR', 'WARN', 'WARNING', 'INFO', 'DEBUG']

argschema.fields.numpyarrays module

marshmallow fields related to reading in numpy arrays

class argschema.fields.numpyarrays.NumpyArray(dtype=None, *args, **kwargs)

Bases: marshmallow.fields.List

NumpyArray is a marshmallow.fields.List subclass which will convert any numpy compatible set of lists into a numpy array after deserialization and convert it back to a list when serializing,

Parameters:dtype (numpy.Dtype) – dtype specifying the desired data type. if dtype is given the array will be converted to the type, otherwise numpy will decide what type it should be. (Default=None)

argschema.fields.slice module

class argschema.fields.slice.Slice(**kwargs)

Bases: marshmallow.fields.String

Slice is a :class:’marshmallow.fields.Str’ field that supports a range or slice argument for selecting some subset of a larger dataset. The syntax is identical to numpy slicing. Examples: “10:20”, “40”, “:30”, “10:2:40”

Parameters:kwargs – the same as any Str receive

Module contents

sub-module for custom marshmallow fields of general utility

class argschema.fields.Field(default=<marshmallow.missing>, attribute=None, load_from=None, dump_to=None, error=None, validate=None, required=False, allow_none=None, load_only=False, dump_only=False, missing=<marshmallow.missing>, error_messages=None, **metadata)[source]

Bases: marshmallow.base.FieldABC

Basic field from which other fields should extend. It applies no formatting by default, and should only be used in cases where data does not need to be formatted before being serialized or deserialized. On error, the name of the field will be returned.

Parameters:
  • default – If set, this value will be used during serialization if the input value is missing. If not set, the field will be excluded from the serialized output if the input value is missing. May be a value or a callable.
  • attribute (str) – The name of the attribute to get the value from. If None, assumes the attribute has the same name as the field.
  • load_from (str) – Additional key to look for when deserializing. Will only be checked if the field’s name is not found on the input dictionary. If checked, it will return this parameter on error.
  • dump_to (str) – Field name to use as a key when serializing.
  • validate (callable) – Validator or collection of validators that are called during deserialization. Validator takes a field’s input value as its only parameter and returns a boolean. If it returns False, an ValidationError is raised.
  • required – Raise a ValidationError if the field value is not supplied during deserialization.
  • allow_none – Set this to True if None should be considered a valid value during validation/deserialization. If missing=None and allow_none is unset, will default to True. Otherwise, the default is False.
  • load_only (bool) – If True skip this field during serialization, otherwise its value will be present in the serialized data.
  • dump_only (bool) – If True skip this field during deserialization, otherwise its value will be present in the deserialized object. In the context of an HTTP API, this effectively marks the field as “read-only”.
  • missing – Default deserialization value for the field if the field is not found in the input data. May be a value or a callable.
  • error_messages (dict) – Overrides for Field.default_error_messages.
  • metadata – Extra arguments to be stored as metadata.

Changed in version 2.0.0: Removed error parameter. Use error_messages instead.

Changed in version 2.0.0: Added allow_none parameter, which makes validation/deserialization of None consistent across fields.

Changed in version 2.0.0: Added load_only and dump_only parameters, which allow field skipping during the (de)serialization process.

Changed in version 2.0.0: Added missing parameter, which indicates the value for a field if the field is not found during deserialization.

Changed in version 2.0.0: default value is only used if explicitly set. Otherwise, missing values inputs are excluded from serialized output.

context

The context dictionary for the parent Schema.

default_error_messages = {u'null': u'Field may not be null.', u'required': u'Missing data for required field.', u'type': u'Invalid input type.', u'validator_failed': u'Invalid value.'}

Default error messages for various kinds of errors. The keys in this dictionary are passed to Field.fail. The values are error messages passed to marshmallow.ValidationError.

deserialize(value, attr=None, data=None)[source]

Deserialize value.

Raises:ValidationError – If an invalid value is passed or if a required value is missing.
fail(key, **kwargs)[source]

A helper method that simply raises a ValidationError.

get_value(attr, obj, accessor=None, default=<marshmallow.missing>)[source]

Return the value for a given key from an object.

root

Reference to the Schema that this field belongs to even if it is buried in a List. Return None for unbound fields.

serialize(attr, obj, accessor=None)[source]

Pulls the value for the given key from the object, applies the field’s formatting and returns the result.

Parameters:
  • attr (str) – The attibute or key to get from the object.
  • obj (str) – The object to pull the key from.
  • accessor (callable) – Function used to pull values from obj.
Raises:

ValidationError – In case of formatting problem

class argschema.fields.Raw(default=<marshmallow.missing>, attribute=None, load_from=None, dump_to=None, error=None, validate=None, required=False, allow_none=None, load_only=False, dump_only=False, missing=<marshmallow.missing>, error_messages=None, **metadata)[source]

Bases: marshmallow.fields.Field

Field that applies no formatting or validation.

class argschema.fields.Nested(nested, default=<marshmallow.missing>, exclude=(), only=None, **kwargs)[source]

Bases: marshmallow.fields.Field

Allows you to nest a Schema inside a field.

Examples:

user = fields.Nested(UserSchema)
user2 = fields.Nested('UserSchema')  # Equivalent to above
collaborators = fields.Nested(UserSchema, many=True, only='id')
parent = fields.Nested('self')

When passing a Schema <marshmallow.Schema> instance as the first argument, the instance’s exclude, only, and many attributes will be respected.

Therefore, when passing the exclude, only, or many arguments to fields.Nested, you should pass a Schema <marshmallow.Schema> class (not an instance) as the first argument.

# Yes
author = fields.Nested(UserSchema, only=('id', 'name'))

# No
author = fields.Nested(UserSchema(), only=('id', 'name'))
Parameters:
  • nested (Schema) – The Schema class or class name (string) to nest, or "self" to nest the Schema within itself.
  • exclude (tuple) – A list or tuple of fields to exclude.
  • required – Raise an ValidationError during deserialization if the field, and any required field values specified in the nested schema, are not found in the data. If not a bool (e.g. a str), the provided value will be used as the message of the ValidationError instead of the default message.
  • only – A tuple or string of the field(s) to marshal. If None, all fields will be marshalled. If a field name (string) is given, only a single value will be returned as output instead of a dictionary. This parameter takes precedence over exclude.
  • many (bool) – Whether the field is a collection of objects.
  • kwargs – The same keyword arguments that Field receives.
default_error_messages = {u'type': u'Invalid type.'}
schema

The nested Schema object.

Changed in version 1.0.0: Renamed from serializer to schema

class argschema.fields.Dict(default=<marshmallow.missing>, attribute=None, load_from=None, dump_to=None, error=None, validate=None, required=False, allow_none=None, load_only=False, dump_only=False, missing=<marshmallow.missing>, error_messages=None, **metadata)[source]

Bases: marshmallow.fields.Field

A dict field. Supports dicts and dict-like objects.

Note

This field is only appropriate when the structure of nested data is not known. For structured data, use Nested.

New in version 2.1.0.

default_error_messages = {u'invalid': u'Not a valid mapping type.'}
class argschema.fields.List(cls_or_instance, **kwargs)[source]

Bases: marshmallow.fields.Field

A list field, composed with another Field class or instance.

Example:

numbers = fields.List(fields.Float())
Parameters:
  • cls_or_instance (Field) – A field class or instance.
  • default (bool) – Default value for serialization.
  • kwargs – The same keyword arguments that Field receives.

Changed in version 2.0.0: The allow_none parameter now applies to deserialization and has the same semantics as the other fields.

default_error_messages = {u'invalid': u'Not a valid list.'}
get_value(attr, obj, accessor=None)[source]

Return the value for a given key from an object.

class argschema.fields.String(default=<marshmallow.missing>, attribute=None, load_from=None, dump_to=None, error=None, validate=None, required=False, allow_none=None, load_only=False, dump_only=False, missing=<marshmallow.missing>, error_messages=None, **metadata)[source]

Bases: marshmallow.fields.Field

A string field.

Parameters:kwargs – The same keyword arguments that Field receives.
default_error_messages = {u'invalid': u'Not a valid string.', u'invalid_utf8': u'Not a valid utf-8 string.'}
class argschema.fields.UUID(default=<marshmallow.missing>, attribute=None, load_from=None, dump_to=None, error=None, validate=None, required=False, allow_none=None, load_only=False, dump_only=False, missing=<marshmallow.missing>, error_messages=None, **metadata)[source]

Bases: marshmallow.fields.String

A UUID field.

default_error_messages = {u'invalid_guid': u'Not a valid UUID.', u'invalid_uuid': u'Not a valid UUID.'}
class argschema.fields.Number(as_string=False, **kwargs)[source]

Bases: marshmallow.fields.Field

Base class for number fields.

Parameters:
  • as_string (bool) – If True, format the serialized value as a string.
  • kwargs – The same keyword arguments that Field receives.
default_error_messages = {u'invalid': u'Not a valid number.'}
num_type

alias of __builtin__.float

class argschema.fields.Integer(as_string=False, **kwargs)[source]

Bases: marshmallow.fields.Number

An integer field.

Parameters:kwargs – The same keyword arguments that Number receives.
default_error_messages = {u'invalid': u'Not a valid integer.'}
num_type

alias of __builtin__.int

class argschema.fields.Decimal(places=None, rounding=None, allow_nan=False, as_string=False, **kwargs)[source]

Bases: marshmallow.fields.Number

A field that (de)serializes to the Python decimal.Decimal type. It’s safe to use when dealing with money values, percentages, ratios or other numbers where precision is critical.

Warning

This field serializes to a decimal.Decimal object by default. If you need to render your data as JSON, keep in mind that the json module from the standard library does not encode decimal.Decimal. Therefore, you must use a JSON library that can handle decimals, such as simplejson, or serialize to a string by passing as_string=True.

Warning

If a JSON float value is passed to this field for deserialization it will first be cast to its corresponding string value before being deserialized to a decimal.Decimal object. The default __str__ implementation of the built-in Python float type may apply a destructive transformation upon its input data and therefore cannot be relied upon to preserve precision. To avoid this, you can instead pass a JSON string to be deserialized directly.

Parameters:
  • places (int) – How many decimal places to quantize the value. If None, does not quantize the value.
  • rounding – How to round the value during quantize, for example decimal.ROUND_UP. If None, uses the rounding value from the current thread’s context.
  • allow_nan (bool) – If True, NaN, Infinity and -Infinity are allowed, even though they are illegal according to the JSON specification.
  • as_string (bool) – If True, serialize to a string instead of a Python decimal.Decimal type.
  • kwargs – The same keyword arguments that Number receives.

New in version 1.2.0.

default_error_messages = {u'special': u'Special numeric values are not permitted.'}
num_type

alias of decimal.Decimal

class argschema.fields.Boolean(default=<marshmallow.missing>, attribute=None, load_from=None, dump_to=None, error=None, validate=None, required=False, allow_none=None, load_only=False, dump_only=False, missing=<marshmallow.missing>, error_messages=None, **metadata)[source]

Bases: marshmallow.fields.Field

A boolean field.

Parameters:kwargs – The same keyword arguments that Field receives.
default_error_messages = {u'invalid': u'Not a valid boolean.'}
falsy = set([0, u'False', u'F', u'f', u'FALSE', u'0', u'false'])

Values that will (de)serialize to False.

truthy = set([1, u'true', u'1', u't', u'True', u'TRUE', u'T'])
class argschema.fields.FormattedString(src_str, *args, **kwargs)[source]

Bases: marshmallow.fields.Field

Interpolate other values from the object into this field. The syntax for the source string is the same as the string str.format method from the python stdlib.

class UserSchema(Schema):
    name = fields.String()
    greeting = fields.FormattedString('Hello {name}')

ser = UserSchema()
res = ser.dump(user)
res.data  # => {'name': 'Monty', 'greeting': 'Hello Monty'}
default_error_messages = {u'format': u'Cannot format string with given data.'}
class argschema.fields.Float(as_string=False, **kwargs)[source]

Bases: marshmallow.fields.Number

A double as IEEE-754 double precision string.

Parameters:
  • as_string (bool) – If True, format the value as a string.
  • kwargs – The same keyword arguments that Number receives.
num_type

alias of __builtin__.float

class argschema.fields.DateTime(format=None, **kwargs)[source]

Bases: marshmallow.fields.Field

A formatted datetime string in UTC.

Example: '2014-12-22T03:12:58.019077+00:00'

Timezone-naive datetime objects are converted to UTC (+00:00) by Schema.dump. Schema.load returns datetime objects that are timezone-aware.

Parameters:
  • format (str) – Either "rfc" (for RFC822), "iso" (for ISO8601), or a date format string. If None, defaults to “iso”.
  • kwargs – The same keyword arguments that Field receives.
DATEFORMAT_DESERIALIZATION_FUNCS = {u'iso': <function from_iso at 0x7fdf1614eed8>, u'iso8601': <function from_iso at 0x7fdf1614eed8>, u'rfc': <function from_rfc at 0x7fdf1614ee60>, u'rfc822': <function from_rfc at 0x7fdf1614ee60>}
DATEFORMAT_SERIALIZATION_FUNCS = {u'iso': <function isoformat at 0x7fdf1614ed70>, u'iso8601': <function isoformat at 0x7fdf1614ed70>, u'rfc': <function rfcformat at 0x7fdf1614ecf8>, u'rfc822': <function rfcformat at 0x7fdf1614ecf8>}
DEFAULT_FORMAT = u'iso'
default_error_messages = {u'format': u'"{input}" cannot be formatted as a datetime.', u'invalid': u'Not a valid datetime.'}
localtime = False
class argschema.fields.LocalDateTime(format=None, **kwargs)[source]

Bases: marshmallow.fields.DateTime

A formatted datetime string in localized time, relative to UTC.

ex. "Sun, 10 Nov 2013 08:23:45 -0600"

Takes the same arguments as DateTime.

localtime = True
class argschema.fields.Time(default=<marshmallow.missing>, attribute=None, load_from=None, dump_to=None, error=None, validate=None, required=False, allow_none=None, load_only=False, dump_only=False, missing=<marshmallow.missing>, error_messages=None, **metadata)[source]

Bases: marshmallow.fields.Field

ISO8601-formatted time string.

Parameters:kwargs – The same keyword arguments that Field receives.
default_error_messages = {u'format': u'"{input}" cannot be formatted as a time.', u'invalid': u'Not a valid time.'}
class argschema.fields.Date(default=<marshmallow.missing>, attribute=None, load_from=None, dump_to=None, error=None, validate=None, required=False, allow_none=None, load_only=False, dump_only=False, missing=<marshmallow.missing>, error_messages=None, **metadata)[source]

Bases: marshmallow.fields.Field

ISO8601-formatted date string.

Parameters:kwargs – The same keyword arguments that Field receives.
default_error_messages = {u'format': u'"{input}" cannot be formatted as a date.', u'invalid': u'Not a valid date.'}
class argschema.fields.TimeDelta(precision=u'seconds', error=None, **kwargs)[source]

Bases: marshmallow.fields.Field

A field that (de)serializes a datetime.timedelta object to an integer and vice versa. The integer can represent the number of days, seconds or microseconds.

Parameters:
  • precision (str) – Influences how the integer is interpreted during (de)serialization. Must be ‘days’, ‘seconds’ or ‘microseconds’.
  • error (str) – Error message stored upon validation failure.
  • kwargs – The same keyword arguments that Field receives.

Changed in version 2.0.0: Always serializes to an integer value to avoid rounding errors. Add precision parameter.

DAYS = u'days'
MICROSECONDS = u'microseconds'
SECONDS = u'seconds'
default_error_messages = {u'format': u'{input!r} cannot be formatted as a timedelta.', u'invalid': u'Not a valid period of time.'}
class argschema.fields.Url(relative=False, schemes=None, **kwargs)[source]

Bases: marshmallow.fields.ValidatedField, marshmallow.fields.String

A validated URL field. Validation occurs during both serialization and deserialization.

Parameters:
  • default – Default value for the field if the attribute is not set.
  • attribute (str) – The name of the attribute to get the value from. If None, assumes the attribute has the same name as the field.
  • relative (bool) – Allow relative URLs.
  • kwargs – The same keyword arguments that String receives.
default_error_messages = {u'invalid': u'Not a valid URL.'}
argschema.fields.URL

alias of marshmallow.fields.Url

class argschema.fields.Email(*args, **kwargs)[source]

Bases: marshmallow.fields.ValidatedField, marshmallow.fields.String

A validated email field. Validation occurs during both serialization and deserialization.

Parameters:
  • args – The same positional arguments that String receives.
  • kwargs – The same keyword arguments that String receives.
default_error_messages = {u'invalid': u'Not a valid email address.'}
class argschema.fields.Method(serialize=None, deserialize=None, method_name=None, **kwargs)[source]

Bases: marshmallow.fields.Field

A field that takes the value returned by a Schema method.

Parameters:
  • method_name (str) – The name of the Schema method from which to retrieve the value. The method must take an argument obj (in addition to self) that is the object to be serialized.
  • deserialize (str) – Optional name of the Schema method for deserializing a value The method must take a single argument value, which is the value to deserialize.

Changed in version 2.0.0: Removed optional context parameter on methods. Use self.context instead.

Changed in version 2.3.0: Deprecated method_name parameter in favor of serialize and allow serialize to not be passed at all.

class argschema.fields.Function(serialize=None, deserialize=None, func=None, **kwargs)[source]

Bases: marshmallow.fields.Field

A field that takes the value returned by a function.

Parameters:
  • serialize (callable) – A callable from which to retrieve the value. The function must take a single argument obj which is the object to be serialized. It can also optionally take a context argument, which is a dictionary of context variables passed to the serializer. If no callable is provided then the `load_only` flag will be set to True.
  • deserialize (callable) – A callable from which to retrieve the value. The function must take a single argument value which is the value to be deserialized. It can also optionally take a context argument, which is a dictionary of context variables passed to the deserializer. If no callable is provided then `value` will be passed through unchanged.
  • func (callable) – This argument is to be deprecated. It exists for backwards compatiblity. Use serialize instead.

Changed in version 2.3.0: Deprecated func parameter in favor of serialize.

argschema.fields.Str

alias of marshmallow.fields.String

argschema.fields.Bool

alias of marshmallow.fields.Boolean

argschema.fields.Int

alias of marshmallow.fields.Integer

class argschema.fields.Constant(constant, **kwargs)[source]

Bases: marshmallow.fields.Field

A field that (de)serializes to a preset constant. If you only want the constant added for serialization or deserialization, you should use dump_only=True or load_only=True respectively.

Parameters:constant – The constant to return for the field attribute.

New in version 2.0.0.

class argschema.fields.OutputFile(default=<marshmallow.missing>, attribute=None, load_from=None, dump_to=None, error=None, validate=None, required=False, allow_none=None, load_only=False, dump_only=False, missing=<marshmallow.missing>, error_messages=None, **metadata)

Bases: marshmallow.fields.String

OutputFile marshmallow.fields.Str subclass which is a path to a
file location that can be written to by the current user (presently tested by opening a temporary file to that location)
class argschema.fields.InputDir(default=<marshmallow.missing>, attribute=None, load_from=None, dump_to=None, error=None, validate=None, required=False, allow_none=None, load_only=False, dump_only=False, missing=<marshmallow.missing>, error_messages=None, **metadata)

Bases: marshmallow.fields.String

InputDir is marshmallow.fields.Str subclass which is a path to a a directory that exists and that the user can access (presently checked with os.access)

class argschema.fields.InputFile(default=<marshmallow.missing>, attribute=None, load_from=None, dump_to=None, error=None, validate=None, required=False, allow_none=None, load_only=False, dump_only=False, missing=<marshmallow.missing>, error_messages=None, **metadata)

Bases: marshmallow.fields.String

InputDile is a marshmallow.fields.Str subclass which is a path to a file location which can be read by the user (presently passes os.path.isfile and os.access = R_OK)

class argschema.fields.OutputDir(mode=None, *args, **kwargs)

Bases: marshmallow.fields.String

OutputDir is a marshmallow.fields.Str subclass which is a path to a location where this module will write files. Validation will check that the directory exists and create the directory if it is not present, and will fail validation if the directory cannot be created or cannot be written to.

Parameters:
  • mode (str) – mode to create directory
  • *args – smae as passed to marshmallow.fields.Str
  • **kwargs – same as passed to marshmallow.fields.Str
class argschema.fields.NumpyArray(dtype=None, *args, **kwargs)

Bases: marshmallow.fields.List

NumpyArray is a marshmallow.fields.List subclass which will convert any numpy compatible set of lists into a numpy array after deserialization and convert it back to a list when serializing,

Parameters:dtype (numpy.Dtype) – dtype specifying the desired data type. if dtype is given the array will be converted to the type, otherwise numpy will decide what type it should be. (Default=None)
class argschema.fields.OptionList(options, **kwargs)

Bases: marshmallow.fields.Field

OptionList is a marshmallow field which enforces that this field
is one of a finite set of options. OptionList(options,*args,**kwargs) where options is a list of json compatible options which this option will be enforced to belong
Parameters:
  • options (list) – A list of python objects of which this field must be one of
  • kwargs (dict) – the same as any Field receives
class argschema.fields.LogLevel(**kwargs)

Bases: marshmallow.fields.String

LogLevel is a field type that provides a setting for the loglevel of python.logging. This class will both validate the input and also set the input globally. In simple scenarios, a module will not have to do any manipulation of loglevel.

options = ['FATAL', 'CRITICAL', 'ERROR', 'WARN', 'WARNING', 'INFO', 'DEBUG']
class argschema.fields.Slice(**kwargs)

Bases: marshmallow.fields.String

Slice is a :class:’marshmallow.fields.Str’ field that supports a range or slice argument for selecting some subset of a larger dataset. The syntax is identical to numpy slicing. Examples: “10:20”, “40”, “:30”, “10:2:40”

Parameters:kwargs – the same as any Str receive