Table Of Contents

Previous topic

Common Exceptions

Next topic

Interfaces

This Page

Models

In Spyne, models are used to mark how a certain message fragment will be converted to and from which native python format. They are also used to hold both declarative and imperative restrictions.

Spyne has built-in support most common data types and provides an API to those who’d like to implement their own.

Base Classes

class spyne.model._base.AttributesMeta(cls_name, cls_bases, cls_dict)[source]

Bases: type

I hate quirks. So this is a 10-minute attempt to get rid of a one-letter quirk.

class spyne.model._base.ModelBase[source]

Bases: object

The base class for type markers. It defines the model interface for the interface generators to use and also manages class customizations that are mainly used for defining constraints on input values.

class Annotations[source]

Bases: object

The class that holds the annotations for the given type.

appinfo = None

Any object that carries app-specific info.

doc = ''

The public documentation for the given type.

class ModelBase.Attributes[source]

Bases: object

The class that holds the constraints for the given type.

default = None

The default value if the input is None

exc_interface = False

If true, this field will be excluded from the interface document.

exc_mapper = False

If true, this field will be excluded from the table mapper of the parent class.

exc_table = False

If true, this field will be excluded from the table of the parent class.

logged = True

If false, this object will be ignored in log_repr, mostly used for logging purposes.

max_occurs = 1

Can be set to any strictly positive integer. Values greater than 1 will imply an iterable of objects as native python type. Can be set to decimal.Decimal("inf") for arbitrary number of arguments.

min_occurs = 0

Set this to 1 to make this object mandatory. Can be set to any positive integer. Note that an object can still be null or empty, even if it’s there.

nillable = True

Set this to false to reject null values. Synonyms with nullable.

schema_tag = '{http://www.w3.org/2001/XMLSchema}element'

The tag used to add a primitives as child to a complex type in the xml schema.

sqla_column_args = None

A dict that will be passed to SQLAlchemy’s Column constructor as **kwargs.

translations = None

A dict that contains locale codes as keys and translations of field names to that language as values.

classmethod ModelBase.customize(**kwargs)[source]

Duplicates cls and overwrites the values in cls.Attributes with **kwargs and returns the new class.

classmethod ModelBase.get_namespace()[source]

Returns the namespace of the class. Defaults to the python module name.

classmethod ModelBase.get_namespace_prefix(interface)[source]

Returns the namespace prefix for the given interface. The get_namespace_prefix of the interface class generates a prefix if none is defined.

classmethod ModelBase.get_type_name()[source]

Returns the class name unless the __type_name__ attribute is defined.

classmethod ModelBase.get_type_name_ns(interface)[source]

Returns the type name with a namespace prefix, separated by a column.

static ModelBase.resolve_namespace(default_ns)[source]

This call finalizes the namespace assignment. The default namespace is not available until the application calls populate_interface method of the interface generator.

static ModelBase.validate_native(value)[source]

Override this method to do your own input validation on the native value. This is called after converting the incoming string to the native python value.

static ModelBase.validate_string(value)[source]

Override this method to do your own input validation on the input string. This is called before converting the incoming string to the native python value.

class spyne.model._base.SimpleModel[source]

Bases: spyne.model._base.ModelBase

The base class for primitives.

class Attributes[source]

Bases: spyne.model._base.Attributes

The class that holds the constraints for the given type.

values = set([])

The set of possible values for this type.

spyne.model._base.nillable_dict(func)[source]

Decorator that retuns empty dictionary if input is None

spyne.model._base.nillable_iterable(func)[source]

Decorator that retuns [] if input is None.

spyne.model._base.nillable_string(func)[source]

Decorator that retuns None if input is None.

Binary Types

The spyne.model.binary package contains binary type markers.

class spyne.model.binary.ByteArray[source]

Bases: spyne.model._base.SimpleModel

Canonical container for arbitrary data. Every protocol has a different way of encapsulating this type. E.g. xml-based protocols encode this as base64, while HttpRpc just hands it over.

Its native python format is a sequence of str objects for Python 2.x and a sequence of bytes objects for Python 3.x.

class spyne.model.binary.File[source]

Bases: spyne.model._base.SimpleModel

A compact way of dealing with incoming files for protocols with a standard way of encoding file metadata along with binary data. (E.g. Http)

Complex

The spyne.model.complex module contains spyne.model.complex.ComplexBase class and its helper objects and subclasses. These are mainly container classes.

class spyne.model.complex.Alias(**kwargs)[source]

Bases: spyne.model.complex.ComplexModelBase

Different type_name, same _type_info.

class spyne.model.complex.Array(**kwargs)[source]

Bases: spyne.model.complex.ComplexModelBase

This class generates a ComplexModel child that has one attribute that has the same name as the serialized class. It’s contained in a Python list.

class spyne.model.complex.ComplexModel(**kwargs)[source]

Bases: spyne.model.complex.ComplexModelBase

The general complexType factory. The __call__ method of this class will return instances, contrary to primivites where the same call will result in customized duplicates of the original class definition. Those who’d like to customize the class should use the customize method. (see :class:spyne.model.ModelBase).

class spyne.model.complex.ComplexModelBase(**kwargs)[source]

Bases: spyne.model._base.ModelBase

If you want to make a better class type, this is what you should inherit from.

class Attributes[source]

Bases: spyne.model._base.Attributes

ComplexModel-specific attributes

sqla_mapper = None

The sqlalchemy mapper object

sqla_mapper_args = None

A dict that will be passed to sqlalchemy.orm.mapper() constructor as. **kwargs.

sqla_metadata = None

None or sqlalchemy.MetaData instance.

sqla_table = None

The sqlalchemy table object

sqla_table_args = None

A dict that will be passed to sqlalchemy.schema.Table constructor as **kwargs.

table_name = None

Table name.

static ComplexModelBase.alias(type_name, namespace, target)[source]

Return an alias class for the given target class.

This function is a variation on ‘ComplexModel.produce’. The alias will borrow the target’s _type_info.

classmethod ComplexModelBase.customize(**kwargs)[source]

Duplicates cls and overwrites the values in cls.Attributes with **kwargs and returns the new class.

classmethod ComplexModelBase.get_deserialization_instance()[source]

Get an empty native type so that the deserialization logic can set its attributes.

static ComplexModelBase.get_flat_type_info(retval=None)[source]

Returns a _type_info dict that includes members from all base classes.

It’s called a “flat” dict because it flattens all members from the inheritance hierarchy into one dict.

classmethod ComplexModelBase.get_serialization_instance(value)[source]

Returns the native object corresponding to the serialized form passed in the value argument.

Parameters:value

This argument can be: * A list or tuple of native types aligned with cls._type_info. * A dict of native types. * The native type itself.

If the value type is not a list, tuple or dict, the value is returned untouched.

static ComplexModelBase.get_simple_type_info(hier_delim='_', retval=None, prefix=None, parent=None)[source]

Returns a _type_info dict that includes members from all base classes and whose types are only primitives. It will prefix field names in non-top-level complex objects with field name of its parent.

For example, given hier_delim=’_’; the following hierarchy:

{‘some_object’: [{‘some_string’: [‘abc’]}]}

would be transformed to:

{‘some_object_some_string’: [‘abc’]}
static ComplexModelBase.produce(namespace, type_name, members)[source]

Lets you create a class programmatically.

class spyne.model.complex.ComplexModelMeta(cls_name, cls_bases, cls_dict)[source]

Bases: type

This metaclass sets _type_info, __type_name__ and __extends__ which are going to be used for (de)serialization and schema generation.

class spyne.model.complex.Iterable(**kwargs)[source]

Bases: spyne.model.complex.Array

This class generates a ComplexModel child that has one attribute that has the same name as the serialized class. It’s contained in a Python iterable. The distinction with the Array is made in the protocol implementation, this is just a marker.

spyne.model.complex.PSSM_VALUES = {'xml': <class spyne.model.complex.xml at 0x2a21ae0>, 'table': <class spyne.model.complex.table at 0x2a21c80>, 'json': <class spyne.model.complex.json at 0x2a21d50>, 'msgpack': <class spyne.model.complex.msgpack at 0x2a21e20>}

Persistent storage serialization method values

class spyne.model.complex.SelfReference[source]

Bases: object

Use this as a placeholder type in classes that contain themselves. See spyne.test.model.test_complex.TestComplexModel.test_self_reference().

spyne.model.complex.TTableModel(metadata=None)[source]

A TableModel template that generates a new TableModel class for each call. If metadata is not supplied, a new one is instantiated.

class spyne.model.complex.XmlAttribute[source]

Bases: spyne.model._base.ModelBase

Items which are marshalled as attributes of the parent element.

class spyne.model.complex.XmlAttributeRef(ref, use=None)[source]

Bases: spyne.model.complex.XmlAttribute

Reference to an Xml attribute.

class spyne.model.complex.json(skip_depth=0)[source]

Complex argument to ComplexModelBase.Attributes.store_as for storing the class instance as a json document.

Make sure you don’t mix this with the json package when importing.

spyne.model.complex.log_repr(obj, cls=None)[source]

Use this function if you want to echo a ComplexModel subclass. It will limit output size of the String types, thus make your logs smaller.

class spyne.model.complex.table(multi=False, left=None, right=None)[source]

Complex argument to ComplexModelBase.Attributes.store_as for storing the class instance as a row in a table in a relational database.

Parameters:
  • multi – When False, configures a one-to-many relationship where the child table has a foreign key to the parent. When != False, configures a many-to-many relationship by creating an intermediate relation table that has foreign keys to both parent and child classes and generates a table name automatically. When True, the table name is generated automatically. Otherwise, it should be a string, as the value is used as the name of the intermediate table.
  • left – Name of the left join column.
  • right – Name of the right join column.
class spyne.model.complex.xml(root_tag=None, no_ns=False)[source]

Complex argument to ComplexModelBase.Attributes.store_as for xml serialization.

Parameters:
  • root_tag – Root tag of the xml element that contains the field values.
  • no_ns – When true, the xml document is stripped from namespace information. use with caution.

Enum

spyne.model.enum.Enum(*values, **kwargs)[source]

The enum type that can only return True when compared to types of own type.

Here’s how it’s supposed to work:

>>> from spyne.model.enum import Enum
>>> SomeEnum = Enum("SomeValue", "SomeOtherValue", type_name="SomeEnum")
>>> SomeEnum.SomeValue == SomeEnum.SomeOtherValue
False
>>> SomeEnum.SomeValue == SomeEnum.SomeValue
True
>>> SomeEnum.SomeValue is SomeEnum.SomeValue
True
>>> SomeEnum.SomeValue == 0
False
>>> SomeEnum2 = Enum("SomeValue", "SomeOtherValue", type_name="SomeEnum")
>>> SomeEnum2.SomeValue == SomeEnum.SomeValue
False

In the above example, SomeEnum can be used as a regular Spyne model.

Fault

class spyne.model.fault.Fault(faultcode='Server', faultstring='', faultactor='', detail=None)[source]

Bases: spyne.model._base.ModelBase, exceptions.Exception

Use this class as a base for all public exceptions. The Fault object adheres to the SOAP 1.1 Fault definition,

which has three main attributes:

Parameters:
  • faultcode

    It’s a dot-delimited string whose first fragment is either ‘Client’ or ‘Server’. Just like HTTP 4xx and 5xx codes, ‘Client’ indicates that something was wrong with the input, and ‘Server’ indicates something went wrong during the processing of an otherwise legitimate request.

    Protocol implementors should heed the values in faultcode to set proper return codes in the protocol level when necessary. E.g. HttpRpc protocol will return a HTTP 404 error when a spyne.error.ResourceNotFound is raised, and a general HTTP 400 when the faultcode starts with 'Client.' or is 'Client'.

    Soap would return Http 500 for any kind of exception, and denote the nature of the exception in the Soap response body. (because that’s what the standard says... Yes, soap is famous for a reason :))

  • faultstring – It’s the human-readable explanation of the exception.
  • detail – Additional information dict.

Primitives

The spyne.model.primitive package contains atomic, single-value types.

class spyne.model.primitive.AnyDict[source]

Bases: spyne.model._base.SimpleModel

A dict instance that can contain other dicts, iterables or primitive types. Its serialization is protocol-dependent.

class spyne.model.primitive.AnyUri[source]

Bases: spyne.model.primitive.Unicode

A special kind of String type designed to hold an uri.

class Value(href, text=None, content=None)[source]

Bases: object

A special object that is just a better way of carrying the information carried with a link.

Parameters:
  • href – The uri string.
  • text – The text data that goes with the link. This is a str or a unicode instance.
  • content – The structured data that goes with the link. This is an lxml.etree.Element instance.
class spyne.model.primitive.AnyXml[source]

Bases: spyne.model._base.SimpleModel

An xml node that can contain any number of sub nodes. It’s represented by an ElementTree object.

class spyne.model.primitive.Boolean[source]

Bases: spyne.model._base.SimpleModel

Life is simple here. Just true or false.

spyne.model.primitive.Byte

alias of Integer8

class spyne.model.primitive.Date[source]

Bases: spyne.model.primitive.DateTime

Just that, Date. No time zone support.

Native type is datetime.date.

class Attributes[source]

Bases: spyne.model.primitive.Attributes

Customizable attributes of the spyne.model.primitive.Date type.

format = '%Y-%m-%d'

DateTime format fed to the strftime function. See: http://docs.python.org/library/datetime.html?highlight=strftime#strftime-strptime-behavior Ignored by protocols like SOAP which have their own ideas about how Date objects should be serialized.

ge = datetime.date(1, 1, 1)

The date should be greater than or equal to this date.

gt = datetime.date(1, 1, 1)

The date should be greater than this date.

le = datetime.date(9999, 12, 31)

The date should be lower than or equal to this date.

lt = datetime.date(9999, 12, 31)

The date should be lower than this date.

pattern = None

A regular expression that matches the whole date. See here for more info: http://www.regular-expressions.info/xml.html

classmethod Date.default_parse(string)[source]

This is used by protocols like SOAP who need ISO8601-formatted dates no matter what.

class spyne.model.primitive.DateTime[source]

Bases: spyne.model._base.SimpleModel

A compact way to represent dates and times together. Supports time zones.

Native type is datetime.datetime.

class Attributes[source]

Bases: spyne.model._base.Attributes

Customizable attributes of the spyne.model.primitive.DateTime type.

format = None

DateTime format fed to the strftime function. See: http://docs.python.org/library/datetime.html?highlight=strftime#strftime-strptime-behavior Ignored by protocols like SOAP which have their own ideas about how DateTime objects should be serialized.

ge = datetime.datetime(1, 1, 1, 0, 0, tzinfo=<UTC>)

The datetime should be greater than or equal to this datetime.

gt = datetime.datetime(1, 1, 1, 0, 0, tzinfo=<UTC>)

The datetime should be greater than this datetime.

le = datetime.datetime(9999, 12, 31, 23, 59, 59, 999999, tzinfo=<UTC>)

The datetime should be lower than or equal to this datetime.

lt = datetime.datetime(9999, 12, 31, 23, 59, 59, 999999, tzinfo=<UTC>)

The datetime should be lower than this datetime.

pattern = None

A regular expression that matches the whole datetime. See here for more info: http://www.regular-expressions.info/xml.html

string_format = None

A regular python string formatting string. %s will contain the date string. See here for more info: http://docs.python.org/library/stdtypes.html#string-formatting

class spyne.model.primitive.Decimal[source]

Bases: spyne.model._base.SimpleModel

The primitive that corresponds to the native python Decimal.

This is also the base class for denoting numbers.

class Attributes[source]

Bases: spyne.model._base.Attributes

Customizable attributes of the spyne.model.primitive.Decimal type.

format = None

A regular python string formatting string. See here: http://docs.python.org/library/stdtypes.html#string-formatting

fraction_digits = Decimal('Infinity')

Maximum number of digits after the decimal separator.

ge = Decimal('-Infinity')

The value should be greater than or equal to this number.

gt = Decimal('-Infinity')

The value should be greater than this number.

le = Decimal('Infinity')

The value should be lower than or equal to this number.

lt = Decimal('Infinity')

The value should be lower than this number.

max_str_len = 1024

The maximum length of string to be attempted to convert to number.

pattern = None

A regular expression that matches the whole field. See here for more info: http://www.regular-expressions.info/xml.html

total_digits = Decimal('Infinity')

Maximum number of digits.

class spyne.model.primitive.Double[source]

Bases: spyne.model.primitive.Decimal

This is serialized as the python float. So this type comes with its gotchas. Unless you really know what you’re doing, you should use a Decimal with a pre-defined number of integer and decimal digits.

class spyne.model.primitive.Duration[source]

Bases: spyne.model._base.SimpleModel

Native type is datetime.timedelta.

class spyne.model.primitive.Float[source]

Bases: spyne.model.primitive.Double

Synonym for Double (as far as python side of things are concerned). It’s here for compatibility reasons.

class spyne.model.primitive.ImageUri[source]

Bases: spyne.model.primitive.AnyUri

A special kind of String that holds the uri of an image.

spyne.model.primitive.Int

alias of Integer32

class spyne.model.primitive.Integer[source]

Bases: spyne.model.primitive.Decimal

The arbitrary-size signed integer.

class spyne.model.primitive.Integer16[source]

Bases: spyne.model.primitive.Integer

The 8-bit signed integer, aka short.

class spyne.model.primitive.Integer32[source]

Bases: spyne.model.primitive.Integer

The 32-bit signed integer, aka int.

class spyne.model.primitive.Integer64[source]

Bases: spyne.model.primitive.Integer

The 64-bit signed integer, aka long.

class spyne.model.primitive.Integer8[source]

Bases: spyne.model.primitive.Integer

The 8-bit signed integer, aka byte.

spyne.model.primitive.Long

alias of Integer64

class spyne.model.primitive.Mandatory[source]

Class that contains mandatory variants of primitives.

spyne.model.primitive.NonNegativeInteger

alias of UnsignedInteger

class spyne.model.primitive.Point[source]

Bases: spyne.model.primitive.Unicode

An experimental point type whose native format is WKT. You can use shapely.wkt.loads() to get a proper point type.

class spyne.model.primitive.Polygon[source]

Bases: spyne.model.primitive.Unicode

An experimental point type whose native format is WKT. You can use shapely.wkt.loads() to get a proper polygon type.

spyne.model.primitive.Short

alias of Integer64

class spyne.model.primitive.Time[source]

Bases: spyne.model._base.SimpleModel

Just that, Time. No time zone support.

Native type is datetime.time.

class Attributes[source]

Bases: spyne.model._base.Attributes

Customizable attributes of the spyne.model.primitive.Time type.

ge = datetime.time(0, 0)

The time should be greater than or equal to this time.

gt = datetime.time(0, 0)

The time should be greater than this time.

le = datetime.time(23, 59, 59, 999999)

The time should be lower than or equal to this time.

lt = datetime.time(23, 59, 59, 999999)

The time should be lower than this time.

pattern = None

A regular expression that matches the whole time. See here for more info: http://www.regular-expressions.info/xml.html

class spyne.model.primitive.Unicode[source]

Bases: spyne.model._base.SimpleModel

The type to represent human-readable data. Its native format is unicode or str with given encoding.

class Attributes[source]

Bases: spyne.model._base.Attributes

Customizable attributes of the spyne.model.primitive.Unicode type.

encoding = None

The encoding of str objects this class may have to deal with.

format = None

A regular python string formatting string. See here: http://docs.python.org/library/stdtypes.html#string-formatting

max_len = Decimal('Infinity')

Maximum length of string. Can be set to decimal.Decimal('inf') to accept strings of arbitrary length. You may also need to adjust spyne.server.wsgi.MAX_CONTENT_LENGTH.

min_len = 0

Minimum length of string. Can be set to any positive integer

pattern = None

A regular expression that matches the whole string. See here for more info: http://www.regular-expressions.info/xml.html

unicode_errors = 'strict'

The argument to the unicode builtin; one of ‘strict’, ‘replace’ or ‘ignore’.

spyne.model.primitive.UnsignedByte

alias of UnsignedInteger8

spyne.model.primitive.UnsignedInt

alias of UnsignedInteger32

class spyne.model.primitive.UnsignedInteger[source]

Bases: spyne.model.primitive.Integer

The arbitrary-size unsigned integer, aka nonNegativeInteger.

class spyne.model.primitive.UnsignedInteger16[source]

Bases: spyne.model.primitive.Integer

The 16-bit unsigned integer, aka unsignedShort.

class spyne.model.primitive.UnsignedInteger32[source]

Bases: spyne.model.primitive.UnsignedInteger

The 32-bit unsigned integer, aka unsignedInt.

class spyne.model.primitive.UnsignedInteger64[source]

Bases: spyne.model.primitive.UnsignedInteger

The 64-bit unsigned integer, aka unsignedLong.

class spyne.model.primitive.UnsignedInteger8[source]

Bases: spyne.model.primitive.Integer

The 8-bit unsigned integer, aka unsignedByte.

spyne.model.primitive.UnsignedLong

alias of UnsignedInteger64

spyne.model.primitive.UnsignedShort

alias of UnsignedInteger16

class spyne.model.primitive.Uuid[source]

Bases: spyne.model._base.Unicode

Unicode subclass for Universially-Unique Identifiers.

SQL Table

This module is DEPRECATED. Create your own TableModel using spyne.model.complex.TTableModel()

class spyne.model.table.TableModel(**kwargs)[source]

Bases: spyne.model.complex.ComplexModelBase

The main base class for complex types shared by both SQLAlchemy and spyne. Classes that inherit from this class should also inherit from an sqlalchemy.declarative base class. See the SQLAlchemy Integration section for more info.

class spyne.model.table.TableModelMeta(classname, bases, dict_)[source]

Bases: sqlalchemy.ext.declarative.api.DeclarativeMeta, spyne.model.complex.ComplexModelMeta

This class uses the information in class definition dictionary to build the _type_info dictionary that spyne relies on. It otherwise leaves SQLAlchemy and its information alone.