1.0 Documentation

XML Stream

«  Stanza Matchers   ::   Contents   ::   Scheduler  »

XML Stream

exception sleekxmpp.xmlstream.xmlstream.RestartStream[source]

Exception to restart stream processing, including resending the stream header.

class sleekxmpp.xmlstream.xmlstream.XMLStream(socket=None, host=u'', port=0)[source]

An XML stream connection manager and event dispatcher.

The XMLStream class abstracts away the issues of establishing a connection with a server and sending and receiving XML “stanzas”. A stanza is a complete XML element that is a direct child of a root document element. Two streams are used, one for each communication direction, over the same socket. Once the connection is closed, both streams should be complete and valid XML documents.

Three types of events are provided to manage the stream:
Stream:Triggered based on received stanzas, similar in concept to events in a SAX XML parser.
Custom:Triggered manually.
Scheduled:Triggered based on time delays.

Typically, stanzas are first processed by a stream event handler which will then trigger custom events to continue further processing, especially since custom event handlers may run in individual threads.

Parameters:
  • socket – Use an existing socket for the stream. Defaults to None to generate a new socket.
  • host (string) – The name of the target server.
  • port (int) – The port to use for the connection. Defaults to 0.
add_event_handler(name, pointer, threaded=False, disposable=False)[source]

Add a custom event handler that will be executed whenever its event is manually triggered.

Parameters:
  • name – The name of the event that will trigger this handler.
  • pointer – The function to execute.
  • threaded – If set to True, the handler will execute in its own thread. Defaults to False.
  • disposable – If set to True, the handler will be discarded after one use. Defaults to False.
add_filter(mode, handler, order=None)[source]

Add a filter for incoming or outgoing stanzas.

These filters are applied before incoming stanzas are passed to any handlers, and before outgoing stanzas are put in the send queue.

Each filter must accept a single stanza, and return either a stanza or None. If the filter returns None, then the stanza will be dropped from being processed for events or from being sent.

Parameters:
  • mode – One of 'in' or 'out'.
  • handler – The filter function.
  • order (int) – The position to insert the filter in the list of active filters.
add_handler(mask, pointer, name=None, disposable=False, threaded=False, filter=False, instream=False)[source]

A shortcut method for registering a handler using XML masks.

The use of register_handler() is preferred.

Parameters:
  • mask – An XML snippet matching the structure of the stanzas that will be passed to this handler.
  • pointer – The handler function itself.
  • disposable – Indicates if the handler should be discarded after one use.
  • threadedDEPRECATED. Remains for backwards compatibility.
  • filterDEPRECATED. Remains for backwards compatibility.
  • instream – Indicates if the handler should execute during stream processing and not during normal event processing.
Parm name:

A unique name for the handler. A name will be generated if one is not provided.

address = None

The desired, or actual, address of the connected server.

auto_reconnect = None

The auto_reconnnect setting controls whether or not the stream will be restarted in the event of an error.

ca_certs = None

Path to a file containing certificates for verifying the server SSL certificate. A non-None value will trigger certificate checking.

Note

On Mac OS X, certificates in the system keyring will be consulted, even if they are not in the provided file.

certfile = None

Path to a file containing a client certificate to use for authenticating via SASL EXTERNAL. If set, there must also be a corresponding :attr:keyfile value.

configure_dns(resolver, domain=None, port=None)[source]

Configure and set options for a Resolver instance, and other DNS related tasks. For example, you can also check getaddrinfo() to see if you need to call out to libresolv.so.2 to run res_init().

Meant to be overridden.

Parameters:
  • resolver – A Resolver instance or None if dnspython is not installed.
  • domain – The initial domain under consideration.
  • port – The initial port under consideration.
configure_socket()[source]

Set timeout and other options for self.socket.

Meant to be overridden.

connect(host=u'', port=0, use_ssl=False, use_tls=True, reattempt=True)[source]

Create a new socket and connect to the server.

Setting reattempt to True will cause connection attempts to be made with an exponential backoff delay (max of reconnect_max_delay which defaults to 10 minute) until a successful connection is established.

Parameters:
  • host – The name of the desired server for the connection.
  • port – Port to connect to on the server.
  • use_ssl – Flag indicating if SSL should be used by connecting directly to a port using SSL.
  • use_tls – Flag indicating if TLS should be used, allowing for connecting to a port without using SSL immediately and later upgrading the connection.
  • reattempt – Flag indicating if the socket should reconnect after disconnections.
default_domain = None

The domain to try when querying DNS records.

default_ns = None

The default namespace of the stream content, not of the stream wrapper itself.

default_port = None

The default port to return when querying DNS records.

del_event_handler(name, pointer)[source]

Remove a function as a handler for an event.

Parameters:
  • name – The name of the event.
  • pointer – The function to remove as a handler.
del_filter(mode, handler)[source]

Remove an incoming or outgoing filter.

disconnect(reconnect=False, wait=None, send_close=True)[source]

Terminate processing and close the XML streams.

Optionally, the connection may be reconnected and resume processing afterwards.

If the disconnect should take place after all items in the send queue have been sent, use wait=True.

Warning

If you are constantly adding items to the queue such that it is never empty, then the disconnect will not occur and the call will continue to block.

Parameters:
  • reconnect – Flag indicating if the connection and processing should be restarted. Defaults to False.
  • wait – Flag indicating if the send queue should be emptied before disconnecting, overriding disconnect_wait.
  • send_close – Flag indicating if the stream footer should be sent before terminating the connection. Setting this to False prevents error loops when trying to disconnect after a socket error.
disconnect_wait = None

The disconnect_wait setting is the default value for controlling if the system waits for the send queue to empty before ending the stream. This may be overridden by passing wait=True or wait=False to disconnect(). The default disconnect_wait value is False.

dns_answers = None

A list of DNS results that have not yet been tried.

dns_service = None

The service name to check with DNS SRV records. For example, setting this to 'xmpp-client' would query the _xmpp-client._tcp service.

end_session_on_disconnect = None

Flag for controlling if the session can be considered ended if the connection is terminated.

event(name, data={}, direct=False)[source]

Manually trigger a custom event.

Parameters:
  • name – The name of the event to trigger.
  • data – Data that will be passed to each event handler. Defaults to an empty dictionary, but is usually a stanza object.
  • direct – Runs the event directly if True, skipping the event queue. All event handlers will run in the same thread.
event_handled(name)[source]

Returns the number of registered handlers for an event.

Parameters:name – The name of the event to check.
event_queue = None

A queue of stream, custom, and scheduled events to be processed.

exception(exception)[source]

Process an unknown exception.

Meant to be overridden.

Parameters:exception – An unhandled exception object.
filesocket = None

A file-like wrapper for the socket for use with the ElementTree module.

getId()

Return the current unique stream ID in hexadecimal form.

getNewId()

Generate and return a new stream ID in hexadecimal form.

Many stanzas, handlers, or matchers may require unique ID values. Using this method ensures that all new ID values are unique in this stream.

get_dns_records(domain, port=None)[source]

Get the DNS records for a domain.

Parameters:
  • domain – The domain in question.
  • port – If the results don’t include a port, use this one.
get_id()[source]

Return the current unique stream ID in hexadecimal form.

incoming_filter(xml)[source]

Filter incoming XML objects before they are processed.

Possible uses include remapping namespaces, or correcting elements from sources with incorrect behavior.

Meant to be overridden.

keyfile = None

Path to a file containing the private key for the selected client certificate to use for authenticating via SASL EXTERNAL.

namespace_map = None

A mapping of XML namespaces to well-known prefixes.

new_id()[source]

Generate and return a new stream ID in hexadecimal form.

Many stanzas, handlers, or matchers may require unique ID values. Using this method ensures that all new ID values are unique in this stream.

pick_dns_answer(domain, port=None)[source]

Pick a server and port from DNS answers.

Gets DNS answers if none available. Removes used answer from available answers.

Parameters:
  • domain – The domain in question.
  • port – If the results don’t include a port, use this one.
process(**kwargs)[source]

Initialize the XML streams and begin processing events.

The number of threads used for processing stream events is determined by HANDLER_THREADS.

Parameters:
  • block (bool) – If False, then event dispatcher will run in a separate thread, allowing for the stream to be used in the background for another application. Otherwise, process(block=True) blocks the current thread. Defaults to False.
  • threaded (bool) – DEPRECATED If True, then event dispatcher will run in a separate thread, allowing for the stream to be used in the background for another application. Defaults to True. This does not mean that no threads are used at all if threaded=False.

Regardless of these threading options, these threads will always exist:

  • The event queue processor
  • The send queue processor
  • The scheduler
proxy_config = None

An optional dictionary of proxy settings. It may provide: :host: The host offering proxy services. :port: The port for the proxy service. :username: Optional username for accessing the proxy. :password: Optional password for accessing the proxy.

reconnect(reattempt=True, wait=False, send_close=True)[source]

Reset the stream’s state and reconnect to the server.

reconnect_delay = None

The current amount to time to delay attempting to reconnect. This value doubles (with some jitter) with each failed connection attempt up to reconnect_max_delay seconds.

reconnect_max_attempts = None

Maximum number of attempts to connect to the server before quitting and raising a ‘connect_failed’ event. Setting to None allows infinite reattempts, while setting it to 0 will disable reconnection attempts. Defaults to None.

reconnect_max_delay = None

Maximum time to delay between connection attempts is one hour.

registerHandler(handler, before=None, after=None)

Add a stream event handler that will be executed when a matching stanza is received.

Parameters:handler – The BaseHandler derived object to execute.
registerStanza(stanza_class)

Add a stanza object class as a known root stanza.

A root stanza is one that appears as a direct child of the stream’s root element.

Stanzas that appear as substanzas of a root stanza do not need to be registered here. That is done using register_stanza_plugin() from sleekxmpp.xmlstream.stanzabase.

Stanzas that are not registered will not be converted into stanza objects, but may still be processed using handlers and matchers.

Parameters:stanza_class – The top-level stanza object’s class.
register_handler(handler, before=None, after=None)[source]

Add a stream event handler that will be executed when a matching stanza is received.

Parameters:handler – The BaseHandler derived object to execute.
register_stanza(stanza_class)[source]

Add a stanza object class as a known root stanza.

A root stanza is one that appears as a direct child of the stream’s root element.

Stanzas that appear as substanzas of a root stanza do not need to be registered here. That is done using register_stanza_plugin() from sleekxmpp.xmlstream.stanzabase.

Stanzas that are not registered will not be converted into stanza objects, but may still be processed using handlers and matchers.

Parameters:stanza_class – The top-level stanza object’s class.
removeHandler(name)

Remove any stream event handlers with the given name.

Parameters:name – The name of the handler.
removeStanza(stanza_class)

Remove a stanza from being a known root stanza.

A root stanza is one that appears as a direct child of the stream’s root element.

Stanzas that are not registered will not be converted into stanza objects, but may still be processed using handlers and matchers.

remove_handler(name)[source]

Remove any stream event handlers with the given name.

Parameters:name – The name of the handler.
remove_stanza(stanza_class)[source]

Remove a stanza from being a known root stanza.

A root stanza is one that appears as a direct child of the stream’s root element.

Stanzas that are not registered will not be converted into stanza objects, but may still be processed using handlers and matchers.

response_timeout = None

The time in seconds to wait before timing out waiting for response stanzas.

schedule(name, seconds, callback, args=None, kwargs=None, repeat=False)[source]

Schedule a callback function to execute after a given delay.

Parameters:
  • name – A unique name for the scheduled callback.
  • seconds – The time in seconds to wait before executing.
  • callback – A pointer to the function to execute.
  • args – A tuple of arguments to pass to the function.
  • kwargs – A dictionary of keyword arguments to pass to the function.
  • repeat – Flag indicating if the scheduled event should be reset and repeat after executing.
scheduler = None

A Scheduler instance for executing callbacks in the future based on time delays.

send(data, mask=None, timeout=None, now=False, use_filters=True)[source]

A wrapper for send_raw() for sending stanza objects.

May optionally block until an expected response is received.

Parameters:
  • data – The ElementBase stanza to send on the stream.
  • maskDEPRECATED An XML string snippet matching the structure of the expected response. Execution will block in this thread until the response is received or a timeout occurs.
  • timeout (int) – Time in seconds to wait for a response before continuing. Defaults to response_timeout.
  • now (bool) – Indicates if the send queue should be skipped, sending the stanza immediately. Useful mainly for stream initialization stanzas. Defaults to False.
  • use_filters (bool) – Indicates if outgoing filters should be applied to the given stanza data. Disabling filters is useful when resending stanzas. Defaults to True.
sendRaw(data, now=False, reconnect=None)

Send raw data across the stream.

Parameters:
  • data (string) – Any string value.
  • reconnect (bool) – Indicates if the stream should be restarted if there is an error sending the stanza. Used mainly for testing. Defaults to auto_reconnect.
sendXML(data, mask=None, timeout=None, now=False)

Send an XML object on the stream, and optionally wait for a response.

Parameters:
  • data – The Element XML object to send on the stream.
  • maskDEPRECATED An XML string snippet matching the structure of the expected response. Execution will block in this thread until the response is received or a timeout occurs.
  • timeout (int) – Time in seconds to wait for a response before continuing. Defaults to response_timeout.
  • now (bool) – Indicates if the send queue should be skipped, sending the stanza immediately. Useful mainly for stream initialization stanzas. Defaults to False.
send_queue = None

A queue of string data to be sent over the stream.

send_raw(data, now=False, reconnect=None)[source]

Send raw data across the stream.

Parameters:
  • data (string) – Any string value.
  • reconnect (bool) – Indicates if the stream should be restarted if there is an error sending the stanza. Used mainly for testing. Defaults to auto_reconnect.
send_xml(data, mask=None, timeout=None, now=False)[source]

Send an XML object on the stream, and optionally wait for a response.

Parameters:
  • data – The Element XML object to send on the stream.
  • maskDEPRECATED An XML string snippet matching the structure of the expected response. Execution will block in this thread until the response is received or a timeout occurs.
  • timeout (int) – Time in seconds to wait for a response before continuing. Defaults to response_timeout.
  • now (bool) – Indicates if the send queue should be skipped, sending the stanza immediately. Useful mainly for stream initialization stanzas. Defaults to False.
session_started_event = None

An Event to signal the start of a stream session. Until this event fires, the send queue is not used and data is sent immediately over the wire.

session_timeout = None

The default time in seconds to wait for a session to start after connecting before reconnecting and trying again.

setSocket(socket, ignore=False)

Set the socket to use for the stream.

The filesocket will be recreated as well.

Parameters:
  • socket – The new socket object to use.
  • ignore (bool) – If True, don’t set the connection state to 'connected'.
set_socket(socket, ignore=False)[source]

Set the socket to use for the stream.

The filesocket will be recreated as well.

Parameters:
  • socket – The new socket object to use.
  • ignore (bool) – If True, don’t set the connection state to 'connected'.
ssl_retry_delay = None

The maximum number of times to attempt resending data due to an SSL error.

ssl_retry_max = None

The time in seconds to delay between attempts to resend data after an SSL error.

ssl_version = None

Most XMPP servers support TLSv1, but OpenFire in particular does not work well with it. For OpenFire, set ssl_version to use SSLv23:

import ssl
xmpp.ssl_version = ssl.PROTOCOL_SSLv23
startTLS()

Perform handshakes for TLS.

If the handshake is successful, the XML stream will need to be restarted.

start_stream_handler(xml)[source]

Perform any initialization actions, such as handshakes, once the stream header has been sent.

Meant to be overridden.

start_tls()[source]

Perform handshakes for TLS.

If the handshake is successful, the XML stream will need to be restarted.

state = None

The connection state machine tracks if the stream is 'connected' or 'disconnected'.

stop = None

An Event to signal that the application is stopping, and that all threads should shutdown.

stream_end_event = None

An Event to signal receiving a closing stream tag from the server.

The default closing tag for the stream element.

stream_header = None

The default opening tag for the stream element.

stream_ns = None

The namespace of the enveloping stream element.

use_cdata = None

Use CDATA for escaping instead of XML entities. Defaults to False.

use_ipv6 = None

If set to True, attempt to use IPv6.

use_proxy = None

If set to True, attempt to connect through an HTTP proxy based on the settings in proxy_config.

use_signals(signals=None)[source]

Register signal handlers for SIGHUP and SIGTERM.

By using signals, a 'killed' event will be raised when the application is terminated.

If a signal handler already existed, it will be executed first, before the 'killed' event is raised.

Parameters:signals (list) – A list of signal names to be monitored. Defaults to ['SIGHUP', 'SIGTERM'].
use_ssl = None

Enable connecting to the server directly over SSL, in particular when the service provides two ports: one for non-SSL traffic and another for SSL traffic.

use_tls = None

Enable connecting to the service without using SSL immediately, but allow upgrading the connection later to use SSL.

wait_timeout = None

The time in seconds to wait for events from the event queue, and also the time between checks for the process stop signal.

whitespace_keepalive = None

If True, periodically send a whitespace character over the wire to keep the connection alive. Mainly useful for connections traversing NAT.

whitespace_keepalive_interval = None

The default interval between keepalive signals when whitespace_keepalive is enabled.

«  Stanza Matchers   ::   Contents   ::   Scheduler  »