XML Stream

1.0 Documentation

«  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.

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 every second 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.
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.
disconnect(reconnect=False, wait=None)[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.
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.
exception(exception)[source]

Process an unknown exception.

Meant to be overridden.

Parameters:exception – An unhandled exception object.
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.

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
reconnect(reattempt=True)[source]

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

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.

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.
send(data, mask=None, timeout=None, now=False)[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.
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_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.
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'.
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.

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'].

«  Stanza Matchers   ::   Contents   ::   Scheduler  »

From &yet