Stanza Objects

1.0 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 SleekXMPP 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="SleekXMPP 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="SleekXMPP Bot" />
</query>'

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

>>> iq['disco_info']['identities']
[('client', 'bot', 'SleekXMPP 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

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

Associate a stanza object as a plugin for another stanza.

>>> from sleekxmpp.xmlstream import register_stanza_plugin
>>> register_stanza_plugin(Iq, CustomStanza)
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 sleekxmpp.xmlstream.stanzabase.ElementBase(xml=None, parent=None)[source]

The core of SleekXMPP’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 = set(('to', 'from', 'type', 'body'))
...     sub_interfaces = set(('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 = set(('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:

>>> message['custom'] = 'bar' # Same as using message['custom']['custom']
>>> message['custom']['custom'] # Must use all interfaces
'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 will contain this substanza.
__bool__()[source]

Stanza objects should be treated as True in boolean contexts.

Python 3.x version.

__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. Delete top level XML attribute named foo.
  6. Remove the foo plugin, if it was loaded.
  7. 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__(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. The value of the foo attribute of the XML object.
  7. The plugin named 'foo'
  8. An empty string.
Parameters:attrib (string) – The name of the requested stanza interface.
__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.

__nonzero__()[source]

Stanza objects should be treated as True in boolean contexts.

Python 2.x version.

__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. Set the value of a top level XML attribute named foo.
  7. Attempt to pass the value to a plugin named 'foo' using the plugin’s 'foo' interface.
  8. 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)

_delAttr(name)

Remove a top level attribute of the XML object.

Parameters:name – The name of the attribute.
_delSub(name, all=False)

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.
_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)[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.
_getAttr(name, default='')

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.
_getSubText(name, default='')

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.
_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='')[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.
_setAttr(name, value)

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.
_setSubText(name, text=None, keep=False)

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.
_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)[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.
attrib[source]

Return the stanza object itself.

Older implementations of stanza objects used XML objects directly, requiring the use of .attrib to access attribute values.

Use of the dictionary syntax with the stanza object itself for accessing stanza interfaces is preferred.

Deprecated since version 1.0.

clear()[source]

Remove all XML element contents and plugins.

Any attribute values will be preserved.

enable(attrib)[source]

Enable and initialize a stanza plugin.

Alias for init_plugin().

Parameters:attrib (string) – The plugin_attrib value of the plugin to enable.
find(xpath)[source]

Find an XML object in this stanza given an XPath expression.

Exposes ElementTree interface for backwards compatibility.

Note

Matching on attribute values is not supported in Python 2.6 or Python 3.1

Parameters:xpath (string) – An XPath expression matching a single desired element.
findall(xpath)[source]

Find multiple XML objects in this stanza given an XPath expression.

Exposes ElementTree interface for backwards compatibility.

Note

Matching on attribute values is not supported in Python 2.6 or Python 3.1.

Parameters:xpath (string) – An XPath expression matching multiple desired elements.
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.
getStanzaValues()

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.

initPlugin(attrib)

Enable and initialize a stanza plugin.

Parameters:attrib (string) – The plugin_attrib value of the plugin to enable.
init_plugin(attrib)[source]

Enable and initialize a stanza plugin.

Parameters:attrib (string) – The plugin_attrib value of the plugin to enable.
keys()[source]

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

Allows stanza objects to be used like dictionaries.

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.
next()[source]

Return the next iterable substanza.

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.
setStanzaValues(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.
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.

StanzaBase

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

StanzaBase provides the foundation for all other stanza objects used by SleekXMPP, 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 sleekxmpp.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 sleekxmpp.xmlstream.JID object of the recipient’s JID.
  • sfrom – Optional string or sleekxmpp.xmlstream.JID object of the sender’s JID.
  • sid (string) – Optional ID value for the stanza.
delPayload()

Remove the XML contents of the stanza.

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.

getFrom()

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

getPayload()

Return a list of XML objects contained in the stanza.

getTo()

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

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.

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(now=False)[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.
setFrom(value)

Set the ‘from’ attribute of the stanza.

Arguments:
from – A string or JID object representing the sender’s JID.
setPayload(value)

Add XML content to the stanza.

Parameters:value – Either an XML or a stanza object, or a list of XML or stanza objects.
setTo(value)

Set the 'to' attribute of the stanza.

Parameters:value – A string or sleekxmpp.xmlstream.JID object representing the recipient’s JID.
setType(value)

Set the stanza’s 'type' attribute.

Only type values contained in types are accepted.

Parameters:value (string) – One of the values contained in types
set_from(value)[source]

Set the ‘from’ attribute of the stanza.

Arguments:
from – 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 sleekxmpp.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 (string) – One of the values contained in types
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