Stanza Objects

1.4 Documentation

«  Jabber IDs (JID)   ::   Contents   ::   Stanza Handlers  »

Stanza Objects

The stanzabase module provides a wrapper for the standard ElementTree module that makes working with XML less painful. Instead of having to manually move up and down an element tree and insert subelements and attributes, you can interact with an object that behaves like a normal dictionary or JSON object, which silently maps keys to XML attributes and elements behind the scenes.

Overview

The usefulness of this layer grows as the XML you have to work with becomes nested. The base unit here, ElementBase, can map to a single XML element, or several depending on how advanced of a mapping is desired from interface keys to XML structures. For example, a single ElementBase derived class could easily describe:

<message to="user@example.com" from="friend@example.com">
  <body>Hi!</body>
  <x:extra>
    <x:item>Custom item 1</x:item>
    <x:item>Custom item 2</x:item>
    <x:item>Custom item 3</x:item>
  </x:extra>
</message>

If that chunk of XML were put in the ElementBase instance msg, we could extract the data from the XML using:

>>> msg['extra']
['Custom item 1', 'Custom item 2', 'Custom item 3']

Provided we set up the handler for the 'extra' interface to load the <x:item> element content into a list.

The key concept is that given an XML structure that will be repeatedly used, we can define a set of interfaces which when we read from, write to, or delete, will automatically manipulate the underlying XML as needed. In addition, some of these interfaces may in turn reference child objects which expose interfaces for particularly complex child elements of the original XML chunk.

Because the stanzabase module was developed as part of an XMPP library, these chunks of XML are referred to as stanzas, and in Slixmpp we refer to a subclass of ElementBase which defines the interfaces needed for interacting with a given stanza a stanza object.

To make dealing with more complicated and nested stanzas or XML chunks easier, stanza objects can be composed in two ways: as iterable child objects or as plugins. Iterable child stanzas, or substanzas, are accessible through a special 'substanzas' interface. This option is useful for stanzas which may contain more than one of the same kind of element. When there is only one child element, the plugin method is more useful. For plugins, a parent stanza object delegates one of its XML child elements to the plugin stanza object. Here is an example:

<iq type="result">
  <query xmlns="http://jabber.org/protocol/disco#info">
    <identity category="client" type="bot" name="Slixmpp Bot" />
  </query>
</iq>

We can can arrange this stanza into two objects: an outer, wrapper object for dealing with the <iq /> element and its attributes, and a plugin object to control the <query /> payload element. If we give the plugin object the name 'disco_info' (using its ElementBase.plugin_attrib value), then we can access the plugin as so:

>>> iq['disco_info']
'<query xmlns="http://jabber.org/protocol/disco#info">
  <identity category="client" type="bot" name="Slixmpp Bot" />
</query>'

We can then drill down through the plugin object’s interfaces as desired:

>>> iq['disco_info']['identities']
[('client', 'bot', 'Slixmpp Bot')]

Plugins may also add new interfaces to the parent stanza object as if they had been defined by the parent directly, and can also override the behaviour of an interface defined by the parent.

Registering Stanza Plugins

slixmpp.xmlstream.stanzabase.register_stanza_plugin(stanza, plugin, iterable=False, overrides=False)[source]

Associate a stanza object as a plugin for another stanza.

>>> from slixmpp.xmlstream import register_stanza_plugin
>>> register_stanza_plugin(Iq, CustomStanza)

Plugin stanzas marked as iterable will be included in the list of substanzas for the parent, using parent['substanzas']. If the attribute plugin_multi_attrib was defined for the plugin, then the substanza set can be filtered to only instances of the plugin class. For example, given a plugin class Foo with plugin_multi_attrib = 'foos' then:

parent['foos']

would return a collection of all Foo substanzas.

Parameters:
  • stanza (class) – The class of the parent stanza.
  • plugin (class) – The class of the plugin stanza.
  • iterable (bool) – Indicates if the plugin stanza should be included in the parent stanza’s iterable 'substanzas' interface results.
  • overrides (bool) – Indicates if the plugin should be allowed to override the interface handlers for the parent stanza, based on the plugin’s overrides field.

New in version 1.0-Beta1: Made register_stanza_plugin the default name. The prior registerStanzaPlugin function name remains as an alias.

ElementBase

class slixmpp.xmlstream.stanzabase.ElementBase(xml=None, parent=None)[source]

The core of Slixmpp’s stanza XML manipulation and handling is provided by ElementBase. ElementBase wraps XML cElementTree objects and enables access to the XML contents through dictionary syntax, similar in style to the Ruby XMPP library Blather’s stanza implementation.

Stanzas are defined by their name, namespace, and interfaces. For example, a simplistic Message stanza could be defined as:

>>> class Message(ElementBase):
...     name = "message"
...     namespace = "jabber:client"
...     interfaces = {'to', 'from', 'type', 'body'}
...     sub_interfaces = {'body'}

The resulting Message stanza’s contents may be accessed as so:

>>> message['to'] = "user@example.com"
>>> message['body'] = "Hi!"
>>> message['body']
"Hi!"
>>> del message['body']
>>> message['body']
""

The interface values map to either custom access methods, stanza XML attributes, or (if the interface is also in sub_interfaces) the text contents of a stanza’s subelement.

Custom access methods may be created by adding methods of the form “getInterface”, “setInterface”, or “delInterface”, where “Interface” is the titlecase version of the interface name.

Stanzas may be extended through the use of plugins. A plugin is simply a stanza that has a plugin_attrib value. For example:

>>> class MessagePlugin(ElementBase):
...     name = "custom_plugin"
...     namespace = "custom"
...     interfaces = {'useful_thing', 'custom'}
...     plugin_attrib = "custom"

The plugin stanza class must be associated with its intended container stanza by using register_stanza_plugin as so:

>>> register_stanza_plugin(Message, MessagePlugin)

The plugin may then be accessed as if it were built-in to the parent stanza:

>>> message['custom']['useful_thing'] = 'foo'

If a plugin provides an interface that is the same as the plugin’s plugin_attrib value, then the plugin’s interface may be assigned directly from the parent stanza, as shown below, but retrieving information will require all interfaces to be used, as so:

>>> # Same as using message['custom']['custom']
>>> message['custom'] = 'bar'
>>> # Must use all interfaces
>>> message['custom']['custom']
'bar'

If the plugin sets is_extension to True, then both setting and getting an interface value that is the same as the plugin’s plugin_attrib value will work, as so:

>>> message['custom'] = 'bar'  # Using is_extension=True
>>> message['custom']
'bar'
Parameters:
  • xml – Initialize the stanza object with an existing XML object.
  • parent – Optionally specify a parent stanza object will contain this substanza.
__bool__()[source]

Stanza objects should be treated as True in boolean contexts.

__copy__()[source]

Return a copy of the stanza object that does not share the same underlying XML object.

__delitem__(attrib)[source]

Delete the value of a stanza interface using dict-like syntax.

Example:

>>> msg['body'] = "Hi!"
>>> msg['body']
'Hi!'
>>> del msg['body']
>>> msg['body']
''

Stanza interfaces are typically mapped directly to the underlyig XML object, but can be overridden by the presence of a del_attrib method (or del_foo where the interface is named 'foo', etc).

The effect of deleting a stanza interface value named foo will be one of:

  1. Call del_foo override handler, if it exists.
  2. Call del_foo, if it exists.
  3. Call delFoo, if it exists.
  4. Delete foo element, if 'foo' is in sub_interfaces.
  5. Remove foo element if 'foo' is in bool_interfaces.
  6. Delete top level XML attribute named foo.
  7. Remove the foo plugin, if it was loaded.
  8. Do nothing.
Parameters:attrib – The name of the affected stanza interface.
__eq__(other)[source]

Compare the stanza object with another to test for equality.

Stanzas are equal if their interfaces return the same values, and if they are both instances of ElementBase.

Parameters:other (ElementBase) – The stanza object to compare against.
__getitem__(full_attrib)[source]

Return the value of a stanza interface using dict-like syntax.

Example:

>>> msg['body']
'Message contents'

Stanza interfaces are typically mapped directly to the underlying XML object, but can be overridden by the presence of a get_attrib method (or get_foo where the interface is named 'foo', etc).

The search order for interface value retrieval for an interface named 'foo' is:

  1. The list of substanzas ('substanzas')
  2. The result of calling the get_foo override handler.
  3. The result of calling get_foo.
  4. The result of calling getFoo.
  5. The contents of the foo subelement, if foo is listed in sub_interfaces.
  6. True or False depending on the existence of a foo subelement and foo is in bool_interfaces.
  7. The value of the foo attribute of the XML object.
  8. The plugin named 'foo'
  9. An empty string.
Parameters:full_attrib (string) – The name of the requested stanza interface.
__init__(xml=None, parent=None)[source]

Initialize self. See help(type(self)) for accurate signature.

__iter__()[source]

Return an iterator object for the stanza’s substanzas.

The iterator is the stanza object itself. Attempting to use two iterators on the same stanza at the same time is discouraged.

__len__()[source]

Return the number of iterable substanzas in this stanza.

__ne__(other)[source]

Compare the stanza object with another to test for inequality.

Stanzas are not equal if their interfaces return different values, or if they are not both instances of ElementBase.

Parameters:other (ElementBase) – The stanza object to compare against.
__next__()[source]

Return the next iterable substanza.

__repr__()[source]

Use the stanza’s serialized XML as its representation.

__setitem__(attrib, value)[source]

Set the value of a stanza interface using dictionary-like syntax.

Example:

>>> msg['body'] = "Hi!"
>>> msg['body']
'Hi!'

Stanza interfaces are typically mapped directly to the underlying XML object, but can be overridden by the presence of a set_attrib method (or set_foo where the interface is named 'foo', etc).

The effect of interface value assignment for an interface named 'foo' will be one of:

  1. Delete the interface’s contents if the value is None.
  2. Call the set_foo override handler, if it exists.
  3. Call set_foo, if it exists.
  4. Call setFoo, if it exists.
  5. Set the text of a foo element, if 'foo' is in sub_interfaces.
  6. Add or remove an empty subelement foo if foo is in bool_interfaces.
  7. Set the value of a top level XML attribute named foo.
  8. Attempt to pass the value to a plugin named 'foo' using the plugin’s 'foo' interface.
  9. Do nothing.
Parameters:
  • attrib (string) – The name of the stanza interface to modify.
  • value – The new value of the stanza interface.
__str__(top_level_ns=True)[source]

Return a string serialization of the underlying XML object.

Parameters:top_level_ns (bool) – Display the top-most namespace. Defaults to True.
__weakref__

list of weak references to the object (if defined)

_del_attr(name)[source]

Remove a top level attribute of the XML object.

Parameters:name – The name of the attribute.
_del_sub(name, all=False, lang=None)[source]

Remove sub elements that match the given name or XPath.

If the element is in a path, then any parent elements that become empty after deleting the element may also be deleted if requested by setting all=True.

Parameters:
  • name – The name or XPath expression for the element(s) to remove.
  • all (bool) – If True, remove all empty elements in the path to the deleted element. Defaults to False.
_get_attr(name, default='')[source]

Return the value of a top level attribute of the XML object.

In case the attribute has not been set, a default value can be returned instead. An empty string is returned if no other default is supplied.

Parameters:
  • name – The name of the attribute.
  • default – Optional value to return if the attribute has not been set. An empty string is returned otherwise.
_get_stanza_values()[source]

Return A JSON/dictionary version of the XML content exposed through the stanza’s interfaces:

>>> msg = Message()
>>> msg.values
{'body': '', 'from': , 'mucnick': '', 'mucroom': '',
'to': , 'type': 'normal', 'id': '', 'subject': ''}

Likewise, assigning to values will change the XML content:

>>> msg = Message()
>>> msg.values = {'body': 'Hi!', 'to': 'user@example.com'}
>>> msg
'<message to="user@example.com"><body>Hi!</body></message>'

New in version 1.0-Beta1.

_get_sub_text(name, default='', lang=None)[source]

Return the text contents of a sub element.

In case the element does not exist, or it has no textual content, a default value can be returned instead. An empty string is returned if no other default is supplied.

Parameters:
  • name – The name or XPath expression of the element.
  • default – Optional default to return if the element does not exists. An empty string is returned otherwise.
_set_attr(name, value)[source]

Set the value of a top level attribute of the XML object.

If the new value is None or an empty string, then the attribute will be removed.

Parameters:
  • name – The name of the attribute.
  • value – The new value of the attribute, or None or ‘’ to remove it.
_set_stanza_values(values)[source]

Set multiple stanza interface values using a dictionary.

Stanza plugin values may be set using nested dictionaries.

Parameters:values – A dictionary mapping stanza interface with values. Plugin interfaces may accept a nested dictionary that will be used recursively.

New in version 1.0-Beta1.

_set_sub_text(name, text=None, keep=False, lang=None)[source]

Set the text contents of a sub element.

In case the element does not exist, a element will be created, and its text contents will be set.

If the text is set to an empty string, or None, then the element will be removed, unless keep is set to True.

Parameters:
  • name – The name or XPath expression of the element.
  • text – The new textual content of the element. If the text is an empty string or None, the element will be removed unless the parameter keep is True.
  • keep – Indicates if the element should be kept if its text is removed. Defaults to False.
append(item)[source]

Append either an XML object or a substanza to this stanza object.

If a substanza object is appended, it will be added to the list of iterable stanzas.

Allows stanza objects to be used like lists.

Parameters:item – Either an XML object or a stanza object to add to this stanza’s contents.
appendxml(xml)[source]

Append an XML object to the stanza’s XML.

The added XML will not be included in the list of iterable substanzas.

Parameters:xml (XML) – The XML object to add to the stanza.
bool_interfaces = {}

A subset of interfaces which maps the presence of subelements to boolean values. Using this set allows for quickly checking for the existence of empty subelements like <required />.

New in version 1.1.

clear()[source]

Remove all XML element contents and plugins.

Any attribute values will be preserved.

enable(attrib, lang=None)[source]

Enable and initialize a stanza plugin.

Alias for init_plugin().

Parameters:attrib (string) – The plugin_attrib value of the plugin to enable.
get(key, default=None)[source]

Return the value of a stanza interface.

If the found value is None or an empty string, return the supplied default value.

Allows stanza objects to be used like dictionaries.

Parameters:
  • key (string) – The name of the stanza interface to check.
  • default – Value to return if the stanza interface has a value of None or "". Will default to returning None.
get_stanza_values()

Return A JSON/dictionary version of the XML content exposed through the stanza’s interfaces:

>>> msg = Message()
>>> msg.values
{'body': '', 'from': , 'mucnick': '', 'mucroom': '',
'to': , 'type': 'normal', 'id': '', 'subject': ''}

Likewise, assigning to values will change the XML content:

>>> msg = Message()
>>> msg.values = {'body': 'Hi!', 'to': 'user@example.com'}
>>> msg
'<message to="user@example.com"><body>Hi!</body></message>'

New in version 1.0-Beta1.

init_plugin(attrib, lang=None, existing_xml=None, reuse=True)[source]

Enable and initialize a stanza plugin.

Parameters:attrib (string) – The plugin_attrib value of the plugin to enable.
interfaces = {'from', 'id', 'payload', 'to', 'type'}

The set of keys that the stanza provides for accessing and manipulating the underlying XML object. This set may be augmented with the plugin_attrib value of any registered stanza plugins.

is_extension = False

If you need to add a new interface to an existing stanza, you can create a plugin and set is_extension = True. Be sure to set the plugin_attrib value to the desired interface name, and that it is the only interface listed in interfaces. Requests for the new interface from the parent stanza will be passed to the plugin directly.

New in version 1.0-Beta5.

iterables = None

A list of child stanzas whose class is included in plugin_iterables.

keys()[source]

Return the names of all stanza interfaces provided by the stanza object.

Allows stanza objects to be used like dictionaries.

lang_interfaces = {}

New in version 1.1.2.

match(xpath)[source]

Compare a stanza object with an XPath-like expression.

If the XPath matches the contents of the stanza object, the match is successful.

The XPath expression may include checks for stanza attributes. For example:

'presence@show=xa@priority=2/status'

Would match a presence stanza whose show value is set to 'xa', has a priority value of '2', and has a status element.

Parameters:xpath (string) – The XPath expression to check against. It may be either a string or a list of element names with attribute checks.
name = 'stanza'

The XML tag name of the element, not including any namespace prefixes. For example, an ElementBase object for <message /> would use name = 'message'.

namespace = 'jabber:client'

The XML namespace for the element. Given <foo xmlns="bar" />, then namespace = "bar" should be used. The default namespace is jabber:client since this is being used in an XMPP library.

next()[source]

Return the next iterable substanza.

overrides = []

In some cases you may wish to override the behaviour of one of the parent stanza’s interfaces. The overrides list specifies the interface name and access method to be overridden. For example, to override setting the parent’s 'condition' interface you would use:

overrides = ['set_condition']

Getting and deleting the 'condition' interface would not be affected.

New in version 1.0-Beta5.

parent = None

A weakref.weakref to the parent stanza, if there is one. If not, then parent is None.

plugin_attrib = 'plugin'

For ElementBase subclasses which are intended to be used as plugins, the plugin_attrib value defines the plugin name. Plugins may be accessed by using the plugin_attrib value as the interface. An example using plugin_attrib = 'foo':

register_stanza_plugin(Message, FooPlugin)
msg = Message()
msg['foo']['an_interface_from_the_foo_plugin']
plugin_attrib_map = {}

A mapping of the plugin_attrib values of registered plugins to their respective classes.

plugin_iterables = {}

The set of stanza classes that can be iterated over using the ‘substanzas’ interface. Classes are added to this set when registering a plugin with iterable=True:

register_stanza_plugin(DiscoInfo, DiscoItem, iterable=True)

New in version 1.0-Beta5.

plugin_multi_attrib = ''

For ElementBase subclasses that are intended to be an iterable group of items, the plugin_multi_attrib value defines an interface for the parent stanza which returns the entire group of matching substanzas. So the following are equivalent:

# Given stanza class Foo, with plugin_multi_attrib = 'foos'
parent['foos']
filter(isinstance(item, Foo), parent['substanzas'])
plugin_overrides = {}

A map of interface operations to the overriding functions. For example, after overriding the set operation for the interface body, plugin_overrides would be:

{'set_body': <some function>}
plugin_tag_map = {}

A mapping of root element tag names (in '{namespace}elementname' format) to the plugin classes responsible for them.

plugins = None

An ordered dictionary of plugin stanzas, mapped by their plugin_attrib value.

pop(index=0)[source]

Remove and return the last substanza in the list of iterable substanzas.

Allows stanza objects to be used like lists.

Parameters:index (int) – The index of the substanza to remove.
set_stanza_values(values)

Set multiple stanza interface values using a dictionary.

Stanza plugin values may be set using nested dictionaries.

Parameters:values – A dictionary mapping stanza interface with values. Plugin interfaces may accept a nested dictionary that will be used recursively.

New in version 1.0-Beta1.

setup(xml=None)[source]

Initialize the stanza’s XML contents.

Will return True if XML was generated according to the stanza’s definition instead of building a stanza object from an existing XML object.

Parameters:xml – An existing XML object to use for the stanza’s content instead of generating new XML.
sub_interfaces = {}

A subset of interfaces which maps interfaces to direct subelements of the underlying XML object. Using this set, the text of these subelements may be set, retrieved, or removed without needing to define custom methods.

tag = None

The name of the tag for the stanza’s root element. It is the same as calling tag_name() and is formatted as '{namespace}elementname'.

classmethod tag_name()[source]

Return the namespaced name of the stanza’s root element.

The format for the tag name is:

'{namespace}elementname'

For example, for the stanza <foo xmlns="bar" />, stanza.tag_name() would return "{bar}foo".

values

Return A JSON/dictionary version of the XML content exposed through the stanza’s interfaces:

>>> msg = Message()
>>> msg.values
{'body': '', 'from': , 'mucnick': '', 'mucroom': '',
'to': , 'type': 'normal', 'id': '', 'subject': ''}

Likewise, assigning to values will change the XML content:

>>> msg = Message()
>>> msg.values = {'body': 'Hi!', 'to': 'user@example.com'}
>>> msg
'<message to="user@example.com"><body>Hi!</body></message>'

New in version 1.0-Beta1.

xml = None

The underlying XML object for the stanza. It is a standard xml.etree.cElementTree object.

xml_ns = 'http://www.w3.org/XML/1998/namespace'

The default XML namespace: http://www.w3.org/XML/1998/namespace.

StanzaBase

class slixmpp.xmlstream.stanzabase.StanzaBase(stream=None, xml=None, stype=None, sto=None, sfrom=None, sid=None, parent=None)[source]

StanzaBase provides the foundation for all other stanza objects used by Slixmpp, and defines a basic set of interfaces common to nearly all stanzas. These interfaces are the 'id', 'type', 'to', and 'from' attributes. An additional interface, 'payload', is available to access the XML contents of the stanza. Most stanza objects will provided more specific interfaces, however.

Stanza Interfaces:

id:An optional id value that can be used to associate stanzas
to:A JID object representing the recipient’s JID.
from:A JID object representing the sender’s JID. with their replies.
type:The type of stanza, typically will be 'normal', 'error', 'get', or 'set', etc.
payload:The XML contents of the stanza.
Parameters:
  • stream (XMLStream) – Optional slixmpp.xmlstream.XMLStream object responsible for sending this stanza.
  • xml (XML) – Optional XML contents to initialize stanza values.
  • stype (string) – Optional stanza type value.
  • sto – Optional string or slixmpp.xmlstream.JID object of the recipient’s JID.
  • sfrom – Optional string or slixmpp.xmlstream.JID object of the sender’s JID.
  • sid (string) – Optional ID value for the stanza.
  • parent – Optionally specify a parent stanza object will contain this substanza.
del_payload()[source]

Remove the XML contents of the stanza.

error()[source]

Set the stanza’s type to 'error'.

exception(e)[source]

Handle exceptions raised during stanza processing.

Meant to be overridden.

get_from()[source]

Return the value of the stanza’s 'from' attribute.

get_payload()[source]

Return a list of XML objects contained in the stanza.

get_to()[source]

Return the value of the stanza’s 'to' attribute.

interfaces = {'from', 'id', 'payload', 'to', 'type'}

There is a small set of attributes which apply to all XMPP stanzas: the stanza type, the to and from JIDs, the stanza ID, and, especially in the case of an Iq stanza, a payload.

namespace = 'jabber:client'

The default XMPP client namespace

reply(clear=True)[source]

Prepare the stanza for sending a reply.

Swaps the 'from' and 'to' attributes.

If clear=True, then also remove the stanza’s contents to make room for the reply content.

For client streams, the 'from' attribute is removed.

Parameters:clear (bool) – Indicates if the stanza’s contents should be removed. Defaults to True.
send()[source]

Queue the stanza to be sent on the XML stream.

Parameters:now (bool) – Indicates if the queue should be skipped and the stanza sent immediately. Useful for stream initialization. Defaults to False.
set_from(value)[source]

Set the ‘from’ attribute of the stanza.

Parameters:from (str or JID) – A string or JID object representing the sender’s JID.
set_payload(value)[source]

Add XML content to the stanza.

Parameters:value – Either an XML or a stanza object, or a list of XML or stanza objects.
set_to(value)[source]

Set the 'to' attribute of the stanza.

Parameters:value – A string or slixmpp.xmlstream.JID object representing the recipient’s JID.
set_type(value)[source]

Set the stanza’s 'type' attribute.

Only type values contained in types are accepted.

Parameters:value (str) – One of the values contained in types
types = {'chat', 'unavailable', 'get', 'set', 'error', None, 'normal'}

A basic set of allowed values for the 'type' interface.

unhandled()[source]

Called if no handlers have been registered to process this stanza.

Meant to be overridden.

«  Jabber IDs (JID)   ::   Contents   ::   Stanza Handlers  »

From &yet