Types

class BaseType(required=False, default=Undefined, serialized_name=None, choices=None, validators=None, deserialize_from=None, export_level=None, serialize_when_none=None, messages=None, metadata=None)

A base class for Types in a Schematics model. Instances of this class may be added to subclasses of Model to define a model schema.

Validators that need to access variables on the instance can be defined be implementing methods whose names start with validate_ and accept one parameter (in addition to self)

Parameters:
  • required – Invalidate field when value is None or is not supplied. Default: False.
  • default – When no data is provided default to this value. May be a callable. Default: None.
  • serialized_name – The name of this field defaults to the class attribute used in the model. However if the field has another name in foreign data set this argument. Serialized data will use this value for the key name too.
  • deserialize_from – A name or list of named fields for which foreign data sets are searched to provide a value for the given field. This only effects inbound data.
  • choices – A list of valid choices. This is the last step of the validator chain.
  • validators – A list of callables. Each callable receives the value after it has been converted into a rich python type. Default: []
  • serialize_when_none – Dictates if the field should appear in the serialized data even if the value is None. Default: None.
  • messages – Override the error messages with a dict. You can also do this by subclassing the Type and defining a MESSAGES dict attribute on the class. A metaclass will merge all the MESSAGES and override the resulting dict with instance level messages and assign to self.messages.
  • metadata

    Dictionary for storing custom metadata associated with the field. To encourage compatibility with external tools, we suggest these keys for common metadata: - label : Brief human-readable label - description : Explanation of the purpose of the field. Used for

    help, tooltips, documentation, etc.
to_native(value, context=None)

Convert untrusted data to a richer Python construct.

to_primitive(value, context=None)

Convert internal data to a value safe to serialize.

validate(value, context=None)

Validate the field and return a converted value or raise a ValidationError with a list of errors raised by the validation chain. Stop the validation process from continuing through the validators by raising StopValidationError instead of ValidationError.

class UUIDType(**kwargs)

A field that stores a valid UUID value.

native_type

alias of uuid.UUID

primitive_type

alias of builtins.str

to_native(value, context=None)

Convert untrusted data to a richer Python construct.

to_primitive(value, context=None)

Convert internal data to a value safe to serialize.

class StringType(regex=None, max_length=None, min_length=None, **kwargs)

A Unicode string field.

native_type

alias of builtins.str

primitive_type

alias of builtins.str

to_native(value, context=None)

Convert untrusted data to a richer Python construct.

class MultilingualStringType(regex=None, max_length=None, min_length=None, default_locale=None, locale_regex='^[a-z]{2}(:?_[A-Z]{2})?$', **kwargs)

A multilanguage string field, stored as a dict with {‘locale’: ‘localized_value’}.

Minimum and maximum lengths apply to each of the localized values.

At least one of default_locale or context.app_data['locale'] must be defined when calling .to_primitive.

native_type

alias of builtins.str

primitive_type

alias of builtins.str

to_native(value, context=None)

Make sure a MultilingualStringType value is a dict or None.

to_primitive(value, context=None)

Use a combination of default_locale and context.app_data['locale'] to return the best localized string.

class NumberType(min_value=None, max_value=None, strict=False, **kwargs)

A generic number field. Converts to and validates against number_type parameter.

to_native(value, context=None)

Convert untrusted data to a richer Python construct.

class IntType(**kwargs)

A field that validates input as an Integer

native_type

alias of builtins.int

primitive_type

alias of builtins.int

LongType

alias of schematics.types.base.IntType

class FloatType(**kwargs)

A field that validates input as a Float

native_type

alias of builtins.float

primitive_type

alias of builtins.float

class DecimalType(min_value=None, max_value=None, strict=False, **kwargs)

A fixed-point decimal number field.

native_type

alias of decimal.Decimal

primitive_type

alias of builtins.str

to_native(value, context=None)

Convert untrusted data to a richer Python construct.

to_primitive(value, context=None)

Convert internal data to a value safe to serialize.

class HashType(regex=None, max_length=None, min_length=None, **kwargs)
to_native(value, context=None)

Convert untrusted data to a richer Python construct.

class MD5Type(regex=None, max_length=None, min_length=None, **kwargs)

A field that validates input as resembling an MD5 hash.

class SHA1Type(regex=None, max_length=None, min_length=None, **kwargs)

A field that validates input as resembling an SHA1 hash.

class BooleanType(**kwargs)

A boolean field type. In addition to True and False, coerces these values:

  • For True: “True”, “true”, “1”
  • For False: “False”, “false”, “0”
native_type

alias of builtins.bool

primitive_type

alias of builtins.bool

to_native(value, context=None)

Convert untrusted data to a richer Python construct.

class GeoPointType(required=False, default=Undefined, serialized_name=None, choices=None, validators=None, deserialize_from=None, export_level=None, serialize_when_none=None, messages=None, metadata=None)

A list storing a latitude and longitude.

native_type

alias of builtins.list

primitive_type

alias of builtins.list

to_native(value, context=None)

Make sure that a geo-value is of type (x, y)

class DateType(formats=None, **kwargs)

Defaults to converting to and from ISO8601 date values.

native_type

alias of datetime.date

primitive_type

alias of builtins.str

to_native(value, context=None)

Convert untrusted data to a richer Python construct.

to_primitive(value, context=None)

Convert internal data to a value safe to serialize.

class DateTimeType(formats=None, serialized_format=None, parser=None, tzd='allow', convert_tz=False, drop_tzinfo=False, **kwargs)

A field that holds a combined date and time value.

The built-in parser accepts input values conforming to the ISO 8601 format <YYYY>-<MM>-<DD>T<hh>:<mm>[:<ss.ssssss>][<z>]. A space may be substituted for the delimiter T. The time zone designator <z> may be either Z or ±<hh>[:][<mm>].

Values are stored as standard datetime.datetime instances with the time zone offset in the tzinfo component if available. Raw values that do not specify a time zone will be converted to naive datetime objects unless tzd='utc' is in effect.

Unix timestamps are also valid input values and will be converted to UTC datetimes.

Parameters:
  • formats – (Optional) A value or iterable of values suitable as datetime.datetime.strptime format strings, for example ('%Y-%m-%dT%H:%M:%S', '%Y-%m-%dT%H:%M:%S.%f'). If the parameter is present, strptime() will be used for parsing instead of the built-in parser.
  • serialized_format – The output format suitable for Python strftime. Default: '%Y-%m-%dT%H:%M:%S.%f%z'
  • parser – (Optional) An external function to use for parsing instead of the built-in parser. It should return a datetime.datetime instance.
  • tzd

    Sets the time zone policy. Default: 'allow'

    'require' Values must specify a time zone.
    'allow' Values both with and without a time zone designator are allowed.
    'utc' Like allow, but values with no time zone information are assumed to be in UTC.
    'reject' Values must not specify a time zone. This also prohibits timestamps.
  • convert_tz

    Indicates whether values with a time zone designator should be automatically converted to UTC. Default: False

    • True: Convert the datetime to UTC based on its time zone offset.
    • False: Don’t convert. Keep the original time and offset intact.
  • drop_tzinfo

    Can be set to automatically remove the tzinfo objects. This option should generally be used in conjunction with the convert_tz option unless you only care about local wall clock times. Default: False

    • True: Discard the tzinfo components and make naive datetime objects instead.
    • False: Preserve the tzinfo components if present.
class fixed_timezone
dst(dt)

datetime -> DST offset in minutes east of UTC.

fromutc(dt)

datetime in UTC -> datetime in local time.

tzname(dt)

datetime -> string name of time zone.

utcoffset(dt)

datetime -> timedelta showing offset from UTC, negative values indicating West of UTC

native_type

alias of datetime.datetime

class offset_timezone(hours=0, minutes=0)
primitive_type

alias of builtins.str

to_native(value, context=None)

Convert untrusted data to a richer Python construct.

to_primitive(value, context=None)

Convert internal data to a value safe to serialize.

class utc_timezone
class UTCDateTimeType(formats=None, parser=None, tzd='utc', convert_tz=True, drop_tzinfo=True, **kwargs)

A variant of DateTimeType that normalizes everything to UTC and stores values as naive datetime instances. By default sets tzd='utc', convert_tz=True, and drop_tzinfo=True. The standard export format always includes the UTC time zone designator "Z".

class TimestampType(formats=None, parser=None, drop_tzinfo=False, **kwargs)

A variant of DateTimeType that exports itself as a Unix timestamp instead of an ISO 8601 string. Always sets tzd='require' and convert_tz=True.

primitive_type

alias of builtins.float

to_primitive(value, context=None)

Convert internal data to a value safe to serialize.

class TimedeltaType(precision='seconds', **kwargs)

Converts Python Timedelta objects into the corresponding value in seconds.

native_type

alias of datetime.timedelta

primitive_type

alias of builtins.float

to_native(value, context=None)

Convert untrusted data to a richer Python construct.

to_primitive(value, context=None)

Convert internal data to a value safe to serialize.

class CompoundType(**kwargs)
to_native(value, context=None)

Convert untrusted data to a richer Python construct.

to_primitive(value, context=None)

Convert internal data to a value safe to serialize.

MultiType

alias of schematics.types.compound.CompoundType

class ModelType(model_spec, **kwargs)

A field that can hold an instance of the specified model.

primitive_type

alias of builtins.dict

class ListType(field, min_size=None, max_size=None, **kwargs)

A field for storing a list of items, all of which must conform to the type specified by the field parameter.

Use it like this:

...
categories = ListType(StringType)
native_type

alias of builtins.list

primitive_type

alias of builtins.list

class DictType(field, coerce_key=None, **kwargs)

A field for storing a mapping of items, the values of which must conform to the type specified by the field parameter.

Use it like this:

...
categories = DictType(StringType)
native_type

alias of builtins.dict

primitive_type

alias of builtins.dict

class PolyModelType(model_spec, **kwargs)

A field that accepts an instance of any of the specified models.

find_model(data)

Finds the intended type by consulting potential classes or claim_function.

primitive_type

alias of builtins.dict

class IPAddressType(regex=None, max_length=None, min_length=None, **kwargs)

A field that stores a valid IPv4 or IPv6 address.

class IPv4Type(regex=None, max_length=None, min_length=None, **kwargs)

A field that stores a valid IPv4 address.

class IPv6Type(regex=None, max_length=None, min_length=None, **kwargs)

A field that stores a valid IPv6 address.

class MACAddressType(regex=None, max_length=None, min_length=None, **kwargs)

A field that stores a valid MAC address.

to_primitive(value, context=None)

Convert internal data to a value safe to serialize.

class URLType(fqdn=True, verify_exists=False, **kwargs)

A field that validates the input as a URL.

Parameters:
  • fqdn – if True the validation function will ensure hostname in URL is a Fully Qualified Domain Name.
  • verify_exists – if True the validation function will make sure the URL is accessible (server responds with HTTP 2xx).
class EmailType(regex=None, max_length=None, min_length=None, **kwargs)

A field that validates input as an E-Mail-Address.

Usage

To learn more about how Types are used, visit Using Types