Types

class schematics.types.base.BaseType(required=False, default=None, serialized_name=None, choices=None, validators=None, deserialize_from=None, serialize_when_none=None, messages=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: True
  • 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.
MESSAGES = {'required': 'This field is required.', 'choices': 'Value must be one of {0}.'}
allow_none()
default
mock(context=None)
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)

Validate the field and return a clean 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 StopValidation instead of ValidationError.

validate_choices(value)
validate_required(value)
class schematics.types.base.BooleanType(required=False, default=None, serialized_name=None, choices=None, validators=None, deserialize_from=None, serialize_when_none=None, messages=None)

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

  • For True: “True”, “true”, “1”
  • For False: “False”, “false”, “0”
FALSE_VALUES = ('False', 'false', '0')
MESSAGES = {'required': 'This field is required.', 'choices': 'Value must be one of {0}.'}
TRUE_VALUES = ('True', 'true', '1')
to_native(value, context=None)
class schematics.types.base.DateTimeType(formats=None, serialized_format=None, **kwargs)

Defaults to converting to and from ISO8601 datetime values.

Parameters:
  • formats – A value or list of values suitable for datetime.datetime.strptime parsing. Default: (‘%Y-%m-%dT%H:%M:%S.%f’, ‘%Y-%m-%dT%H:%M:%S’, ‘%Y-%m-%dT%H:%M:%S.%fZ’, ‘%Y-%m-%dT%H:%M:%SZ’)
  • serialized_format – The output format suitable for Python strftime. Default: '%Y-%m-%dT%H:%M:%S.%f'
DEFAULT_FORMATS = ('%Y-%m-%dT%H:%M:%S.%f', '%Y-%m-%dT%H:%M:%S', '%Y-%m-%dT%H:%M:%S.%fZ', '%Y-%m-%dT%H:%M:%SZ')
MESSAGES = {'required': 'This field is required.', 'choices': 'Value must be one of {0}.', 'parse_formats': 'Could not parse {0}. Valid formats: {1}', 'parse': 'Could not parse {0}. Should be ISO8601.'}
SERIALIZED_FORMAT = '%Y-%m-%dT%H:%M:%S.%f'
to_native(value, context=None)
to_primitive(value, context=None)
class schematics.types.base.DateType(**kwargs)

Defaults to converting to and from ISO8601 date values.

MESSAGES = {'required': 'This field is required.', 'choices': 'Value must be one of {0}.', 'parse': 'Could not parse {0}. Should be ISO8601 (YYYY-MM-DD).'}
SERIALIZED_FORMAT = '%Y-%m-%d'
to_native(value, context=None)
to_primitive(value, context=None)
class schematics.types.base.DecimalType(min_value=None, max_value=None, **kwargs)

A fixed-point decimal number field.

MESSAGES = {'required': 'This field is required.', 'choices': 'Value must be one of {0}.', 'number_max': 'Value should be less than {0}.', 'number_coerce': "Number '{0}' failed to convert to a decimal.", 'number_min': 'Value should be greater than {0}.'}
to_native(value, context=None)
to_primitive(value, context=None)
validate_range(value)
class schematics.types.base.EmailType(regex=None, max_length=None, min_length=None, **kwargs)

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

EMAIL_REGEX = re.compile('(^[-!#$%&\'*+/=?^_`{}|~0-9A-Z]+(\\.[-!#$%&\'*+/=?^_`{}|~0-9A-Z]+)*|^"([\\001-\\010\\013\\014\\016-\\037!#-\\[\\]-\\177]|\\\\[\\001-011\\013\\014\\016-\\177])*")@(?:[A-Z0-9](?:[A-Z0-9-]{0,2000}[A-Z0-9, re.IGNORECASE)
MESSAGES = {'required': 'This field is required.', 'max_length': 'String value is too long.', 'min_length': 'String value is too short.', 'convert': "Couldn't interpret '{0}' as string.", 'email': 'Not a well formed email address.', 'choices': 'Value must be one of {0}.', 'regex': 'String value did not match validation regex.'}
validate_email(value)
class schematics.types.base.FloatType(*args, **kwargs)

A field that validates input as a Float

MESSAGES = {'required': 'This field is required.', 'choices': 'Value must be one of {0}.', 'number_max': '{0} value should be less than {1}.', 'number_coerce': "Value '{0}' is not {1}.", 'number_min': '{0} value should be greater than {1}.'}
class schematics.types.base.GeoPointType(required=False, default=None, serialized_name=None, choices=None, validators=None, deserialize_from=None, serialize_when_none=None, messages=None)

A list storing a latitude and longitude.

MESSAGES = {'required': 'This field is required.', 'choices': 'Value must be one of {0}.'}
to_native(value, context=None)

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

class schematics.types.base.HashType(required=False, default=None, serialized_name=None, choices=None, validators=None, deserialize_from=None, serialize_when_none=None, messages=None)
MESSAGES = {'required': 'This field is required.', 'choices': 'Value must be one of {0}.', 'hash_hex': 'Hash value is not hexadecimal.', 'hash_length': 'Hash value is wrong length.'}
to_native(value, context=None)
class schematics.types.base.IPv4Type(required=False, default=None, serialized_name=None, choices=None, validators=None, deserialize_from=None, serialize_when_none=None, messages=None)

A field that stores a valid IPv4 address

MESSAGES = {'required': 'This field is required.', 'choices': 'Value must be one of {0}.'}
classmethod valid_ip(addr)
validate(value)

Make sure the value is a IPv4 address: http://stackoverflow.com/questions/9948833/validate-ip-address-from-list

class schematics.types.base.IntType(*args, **kwargs)

A field that validates input as an Integer

MESSAGES = {'required': 'This field is required.', 'choices': 'Value must be one of {0}.', 'number_max': '{0} value should be less than {1}.', 'number_coerce': "Value '{0}' is not {1}.", 'number_min': '{0} value should be greater than {1}.'}
class schematics.types.base.LongType(*args, **kwargs)

A field that validates input as a Long

MESSAGES = {'required': 'This field is required.', 'choices': 'Value must be one of {0}.', 'number_max': '{0} value should be less than {1}.', 'number_coerce': "Value '{0}' is not {1}.", 'number_min': '{0} value should be greater than {1}.'}
class schematics.types.base.MD5Type(required=False, default=None, serialized_name=None, choices=None, validators=None, deserialize_from=None, serialize_when_none=None, messages=None)

A field that validates input as resembling an MD5 hash.

LENGTH = 32
MESSAGES = {'required': 'This field is required.', 'choices': 'Value must be one of {0}.', 'hash_hex': 'Hash value is not hexadecimal.', 'hash_length': 'Hash value is wrong length.'}
class schematics.types.base.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['locale'] must be defined when calling .to_primitive.

LOCALE_REGEX = '^[a-z]{2}(:?_[A-Z]{2})?$'
MESSAGES = {'max_length': 'String value in locale {0} is too long.', 'convert': "Couldn't interpret value as string.", 'regex_localized': 'String value in locale {0} did not match validation regex.', 'choices': 'Value must be one of {0}.', 'required': 'This field is required.', 'min_length': 'String value in locale {0} is too short.', 'regex_locale': 'Name of locale {0} did not match validation regex.', 'locale_not_found': 'No requested locale was available.', 'no_locale': 'No default or explicit locales were given.'}
allow_casts = (<class 'int'>, <class '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['locale'] to return the best localized string.

validate_length(value)
validate_regex(value)
class schematics.types.base.NumberType(number_class, number_type, min_value=None, max_value=None, **kwargs)

A number field.

MESSAGES = {'required': 'This field is required.', 'choices': 'Value must be one of {0}.', 'number_max': '{0} value should be less than {1}.', 'number_coerce': "Value '{0}' is not {1}.", 'number_min': '{0} value should be greater than {1}.'}
to_native(value, context=None)
validate_is_a_number(value)
validate_range(value)
class schematics.types.base.SHA1Type(required=False, default=None, serialized_name=None, choices=None, validators=None, deserialize_from=None, serialize_when_none=None, messages=None)

A field that validates input as resembling an SHA1 hash.

LENGTH = 40
MESSAGES = {'required': 'This field is required.', 'choices': 'Value must be one of {0}.', 'hash_hex': 'Hash value is not hexadecimal.', 'hash_length': 'Hash value is wrong length.'}
class schematics.types.base.StringType(regex=None, max_length=None, min_length=None, **kwargs)

A unicode string field. Default minimum length is one. If you want to accept empty strings, init with min_length 0.

MESSAGES = {'required': 'This field is required.', 'max_length': 'String value is too long.', 'min_length': 'String value is too short.', 'convert': "Couldn't interpret '{0}' as string.", 'choices': 'Value must be one of {0}.', 'regex': 'String value did not match validation regex.'}
allow_casts = (<class 'int'>, <class 'str'>)
to_native(value, context=None)
validate_length(value)
validate_regex(value)
class schematics.types.base.TypeMeta

Meta class for BaseType. Merges MESSAGES dict and accumulates validator methods.

class schematics.types.base.URLType(verify_exists=False, **kwargs)

A field that validates input as an URL.

If verify_exists=True is passed the validate function will make sure the URL makes a valid connection.

MESSAGES = {'required': 'This field is required.', 'max_length': 'String value is too long.', 'min_length': 'String value is too short.', 'convert': "Couldn't interpret '{0}' as string.", 'choices': 'Value must be one of {0}.', 'regex': 'String value did not match validation regex.', 'not_found': 'URL does not exist.', 'invalid_url': 'Not a well formed URL.'}
URL_REGEX = re.compile('^https?://(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,2000}[A-Z0-9])?\\.)+[A-Z]{2,63}\\.?|localhost|\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3})(?::\\d+)?(?:/?|[/?]\\S+)$', re.IGNORECASE)
validate_url(value)
class schematics.types.base.UUIDType(required=False, default=None, serialized_name=None, choices=None, validators=None, deserialize_from=None, serialize_when_none=None, messages=None)

A field that stores a valid UUID value.

MESSAGES = {'required': 'This field is required.', 'choices': 'Value must be one of {0}.', 'convert': "Couldn't interpret '{0}' value as UUID."}
to_native(value, context=None)
to_primitive(value, context=None)
schematics.types.base.fill_template(template, min_length, max_length)
schematics.types.base.force_unicode(obj, encoding='utf-8')
schematics.types.base.get_range_endpoints(min_length, max_length, padding=0, required_length=0)
schematics.types.base.get_value_in(min_length, max_length, padding=0, required_length=0)
schematics.types.base.random_string(length, chars='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789')
schematics.types.base.utf8_decode(s)
class schematics.types.compound.DictType(field, coerce_key=None, **kwargs)
MESSAGES = {'required': 'This field is required.', 'choices': 'Value must be one of {0}.'}
export_loop(dict_instance, field_converter, role=None, print_none=False)

Loops over each item in the model and applies either the field transform or the multitype transform. Essentially functions the same as transforms.export_loop.

model_class
to_native(value, safe=False, context=None)
validate_items(items)
class schematics.types.compound.ListType(field, min_size=None, max_size=None, **kwargs)
MESSAGES = {'required': 'This field is required.', 'choices': 'Value must be one of {0}.'}
check_length(value)
export_loop(list_instance, field_converter, role=None, print_none=False)

Loops over each item in the model and applies either the field transform or the multitype transform. Essentially functions the same as transforms.export_loop.

model_class
to_native(value, context=None)
validate_items(items)
class schematics.types.compound.ModelType(model_class, **kwargs)
MESSAGES = {'required': 'This field is required.', 'choices': 'Value must be one of {0}.'}
export_loop(model_instance, field_converter, role=None, print_none=False)

Calls the main export_loop implementation because they are both supposed to operate on models.

to_native(value, mapping=None, context=None)
class schematics.types.compound.MultiType(required=False, default=None, serialized_name=None, choices=None, validators=None, deserialize_from=None, serialize_when_none=None, messages=None)
MESSAGES = {'required': 'This field is required.', 'choices': 'Value must be one of {0}.'}
export_loop(shape_instance, field_converter, role=None, print_none=False)
init_compound_field(field, compound_field, **kwargs)

Some of non-BaseType fields requires field arg. Not avoid name conflict, provide it as compound_field. Example:

comments = ListType(DictType, compound_field=StringType)
validate(value)

Report dictionary of errors with lists of errors as values of each key. Used by ModelType and ListType.

class schematics.types.compound.PolyModelType(model_classes, **kwargs)
MESSAGES = {'required': 'This field is required.', 'choices': 'Value must be one of {0}.'}
export_loop(model_instance, field_converter, role=None, print_none=False)
find_model(data)

Finds the intended type by consulting potential classes or claim_function.

is_allowed_model(model_instance)
to_native(value, mapping=None, context=None)
schematics.types.compound.get_all_subclasses(cls)

Usage

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