autobahn.twisted

Submodules

autobahn.twisted.choosereactor

autobahn.twisted.choosereactor.install_optimal_reactor(verbose=False)[source]

Try to install the optimal Twisted reactor for platform.

Parameters:verbose (bool) – If True, print what happens.
autobahn.twisted.choosereactor.install_reactor(explicitReactor=None, verbose=False)[source]

Install Twisted reactor.

Parameters:
  • explicitReactor (obj) – If provided, install this reactor. Else, install optimal reactor.
  • verbose (bool) – If True, print what happens.

autobahn.twisted.flashpolicy

class autobahn.twisted.flashpolicy.FlashPolicyProtocol(allowedDomain, allowedPorts)[source]

Bases: twisted.internet.protocol.Protocol

Flash Player 9 (version 9.0.124.0 and above) implements a strict new access policy for Flash applications that make Socket or XMLSocket connections to a remote host. It now requires the presence of a socket policy file on the server.

We want this to support the Flash WebSockets bridge which is needed for older browser, in particular MSIE9/8.

Parameters:allowedPort (int) – The port to which Flash player should be allowed to connect.
REQUESTPAT = <_sre.SRE_Pattern object>
REQUESTMAXLEN = 200
REQUESTTIMEOUT = 5
POLICYFILE = '<?xml version="1.0"?><cross-domain-policy><allow-access-from domain="%s" to-ports="%s" /></cross-domain-policy>'
connectionMade()[source]
connectionLost(reason)[source]
dataReceived(data)[source]
class autobahn.twisted.flashpolicy.FlashPolicyFactory(allowedDomain=None, allowedPorts=None, reactor=None)[source]

Bases: twisted.internet.protocol.Factory

Parameters:
  • allowedDomain (str or None) – The domain from which to allow Flash to connect from. If None, allow from anywhere.
  • allowedPorts (list of int or None) – The ports to which Flash player should be allowed to connect. If None, allow any ports.
  • reactor (obj) – Twisted reactor to use. If not given, autoimport.
buildProtocol(addr)

autobahn.twisted.forwarder

class autobahn.twisted.forwarder.DestEndpointForwardingProtocol[source]

Bases: twisted.internet.protocol.Protocol

connectionMade()
dataReceived(data)
connectionLost(reason)
class autobahn.twisted.forwarder.DestEndpointForwardingFactory(sourceProtocol)[source]

Bases: twisted.internet.protocol.Factory

buildProtocol(addr)
class autobahn.twisted.forwarder.EndpointForwardingProtocol[source]

Bases: twisted.internet.protocol.Protocol

connectionMade(*args, **kwargs)
dataReceived(data)
connectionLost(reason)
class autobahn.twisted.forwarder.EndpointForwardingService(endpointDescriptor, destEndpointDescriptor, reactor=None)[source]

Bases: twisted.application.service.Service

startService(*args, **kwargs)
stopService()
class autobahn.twisted.forwarder.Options[source]

Bases: twisted.python.usage.Options

synopsis = '[options]'
longdesc = 'Endpoint Forwarder.'
optParameters = [['endpoint', 'e', None, 'Source endpoint.'], ['dest_endpoint', 'd', None, 'Destination endpoint.']]
autobahn.twisted.forwarder.makeService(config)[source]

autobahn.twisted.longpoll

class autobahn.twisted.longpoll.WampLongPollResource(factory, serializers=None, timeout=10, killAfter=30, queueLimitBytes=131072, queueLimitMessages=100, debug=False, debug_transport_id=None, reactor=None)[source]

Bases: twisted.web.resource.Resource

A WAMP-over-Longpoll resource for use with Twisted Web Resource trees.

This class provides an implementation of the WAMP-over-Longpoll Transport for WAMP.

The Resource exposes the following paths (child resources).

Opening a new WAMP session:

  • <base-url>/open

Once a transport is created and the session is opened:

  • <base-url>/<transport-id>/send
  • <base-url>/<transport-id>/receive
  • <base-url>/<transport-id>/close

Create new HTTP WAMP Web resource.

Parameters:
  • factory (Instance of autobahn.twisted.wamp.RouterSessionFactory.) – A (router) session factory.
  • serializers (list of obj (which implement autobahn.wamp.interfaces.ISerializer)) – List of WAMP serializers.
  • timeout (int) – XHR polling timeout in seconds.
  • killAfter (int) – Kill WAMP session after inactivity in seconds.
  • queueLimitBytes (int) – Kill WAMP session after accumulation of this many bytes in send queue (XHR poll).
  • queueLimitMessages (int) – Kill WAMP session after accumulation of this many message in send queue (XHR poll).
  • debug (bool) – Enable debug logging.
  • debug_transport_id (str) – If given, use this fixed transport ID.
  • reactor (obj) – The Twisted reactor to run under.
protocol

alias of WampLongPollResourceSession

render_GET(request)[source]
getChild(name, request)[source]

Returns send/receive/close resource for transport.

See also

getNotice(peer, redirectUrl=None, redirectAfter=0)[source]

Render a user notice (HTML page) when the Long-Poll root resource is accessed via HTTP/GET (by a user).

Parameters:
  • redirectUrl (str) – Optional URL to redirect the user to.
  • redirectAfter (int) – When redirectUrl is provided, redirect after this time (seconds).

autobahn.twisted.rawsocket

class autobahn.twisted.rawsocket.WampRawSocketServerProtocol[source]

Bases: autobahn.twisted.rawsocket.WampRawSocketProtocol

Base class for Twisted-based WAMP-over-RawSocket server protocols.

class autobahn.twisted.rawsocket.WampRawSocketClientProtocol[source]

Bases: autobahn.twisted.rawsocket.WampRawSocketProtocol

Base class for Twisted-based WAMP-over-RawSocket client protocols.

class autobahn.twisted.rawsocket.WampRawSocketServerFactory(factory, serializer, debug=False)[source]

Bases: autobahn.twisted.rawsocket.WampRawSocketFactory

Base class for Twisted-based WAMP-over-RawSocket server factories.

Parameters:
protocol

alias of WampRawSocketServerProtocol

class autobahn.twisted.rawsocket.WampRawSocketClientFactory(factory, serializer, debug=False)[source]

Bases: autobahn.twisted.rawsocket.WampRawSocketFactory

Base class for Twisted-based WAMP-over-RawSocket client factories.

Parameters:
protocol

alias of WampRawSocketClientProtocol

autobahn.twisted.resource

class autobahn.twisted.resource.HTTPChannelHixie76Aware[source]

Bases: twisted.web.http.HTTPChannel

Hixie-76 is deadly broken. It includes 8 bytes of body, but then does not set content-length header. This hacked HTTPChannel injects the missing HTTP header upon detecting Hixie-76. We need this since otherwise Twisted Web will silently ignore the body.

To use this, set protocol = HTTPChannelHixie76Aware on your twisted.web.server.Site instance.

headerReceived(line)[source]
class autobahn.twisted.resource.WSGIRootResource(wsgiResource, children)[source]

Bases: twisted.web.resource.Resource

Root resource when you want a WSGI resource be the default serving resource for a Twisted Web site, but have subpaths served by different resources.

This is a hack needed since twisted.web.wsgi.WSGIResource. does not provide a putChild() method.

Parameters:
  • wsgiResource – The WSGI to serve as root resource.
  • children (dict) – A dictionary with string keys constituting URL subpaths, and Twisted Web resources as values.
getChild(path, request)[source]
class autobahn.twisted.resource.WebSocketResource(factory)[source]

Bases: object

A Twisted Web resource for WebSocket.

Parameters:factory (obj) – An instance of autobahn.twisted.websocket.WebSocketServerFactory.
isLeaf = True
getChildWithDefault(name, request)[source]

This resource cannot have children, hence this will always fail.

putChild(path, child)[source]

This resource cannot have children, hence this is always ignored.

render(request)[source]

Render the resource. This will takeover the transport underlying the request, create a autobahn.twisted.websocket.WebSocketServerProtocol and let that do any subsequent communication.

autobahn.twisted.util

autobahn.twisted.util.sleep(delay, reactor=None)[source]

Inline sleep for use in coroutines (Twisted inlineCallback decorated functions).

Parameters:
  • delay (float) – Time to sleep in seconds.
  • reactor (None or provider of IReactorTime.) – The Twisted reactor to use.
autobahn.twisted.util.peer2str(addr)[source]

Convert a Twisted address, as returned from self.transport.getPeer() to a string

autobahn.twisted.wamp

class autobahn.twisted.wamp.FutureMixin[source]

Mixin for Twisted style Futures (“Deferreds”).

class autobahn.twisted.wamp.ApplicationSession(config=None)[source]

Bases: autobahn.twisted.wamp.FutureMixin, autobahn.wamp.protocol.ApplicationSession

WAMP application session for Twisted-based applications.

Constructor.

class autobahn.twisted.wamp.ApplicationSessionFactory(config=None)[source]

Bases: autobahn.twisted.wamp.FutureMixin, autobahn.wamp.protocol.ApplicationSessionFactory

WAMP application session factory for Twisted-based applications.

Parameters:config (instance of autobahn.wamp.types.ComponentConfig) – The default component configuration.
session

The application session class this application session factory will use. Defaults to autobahn.twisted.wamp.ApplicationSession.

alias of ApplicationSession

class autobahn.twisted.wamp.ApplicationRunner(url, realm, extra=None, debug=False, debug_wamp=False, debug_app=False)[source]

This class is a convenience tool mainly for development and quick hosting of WAMP application components.

It can host a WAMP application component in a WAMP-over-WebSocket client connecting to a WAMP router.

Parameters:
  • url (unicode) – The WebSocket URL of the WAMP router to connect to (e.g. ws://somehost.com:8090/somepath)
  • realm (unicode) – The WAMP realm to join the application session to.
  • extra (dict) – Optional extra configuration to forward to the application component.
  • debug (bool) – Turn on low-level debugging.
  • debug_wamp (bool) – Turn on WAMP-level debugging.
  • debug_app (bool) – Turn on app-level debugging.
run(make, start_reactor=True)[source]

Run the application component.

Parameters:make (callable) – A factory that produces instances of autobahn.asyncio.wamp.ApplicationSession when called with an instance of autobahn.wamp.types.ComponentConfig.
class autobahn.twisted.wamp.Application(prefix=None)[source]

A WAMP application. The application object provides a simple way of creating, debugging and running WAMP application components.

Parameters:prefix (unicode) – The application URI prefix to use for procedures and topics, e.g. "com.example.myapp".
run(url=u'ws://localhost:8080/ws', realm=u'realm1', debug=False, debug_wamp=False, debug_app=False, start_reactor=True)[source]

Run the application.

Parameters:
  • url (unicode) – The URL of the WAMP router to connect to.
  • realm (unicode) – The realm on the WAMP router to join.
  • debug (bool) – Turn on low-level debugging.
  • debug_wamp (bool) – Turn on WAMP-level debugging.
  • debug_app (bool) – Turn on app-level debugging.
register(uri=None)[source]

Decorator exposing a function as a remote callable procedure.

The first argument of the decorator should be the URI of the procedure to register under.

Example:
@app.register('com.myapp.add2')
def add2(a, b):
   return a + b

Above function can then be called remotely over WAMP using the URI com.myapp.add2 the function was registered under.

If no URI is given, the URI is constructed from the application URI prefix and the Python function name.

Example:
app = Application('com.myapp')

# implicit URI will be 'com.myapp.add2'
@app.register()
def add2(a, b):
   return a + b

If the function yields (is a co-routine), the @inlineCallbacks decorator will be applied automatically to it. In that case, if you wish to return something, you should use returnValue:

Example:
from twisted.internet.defer import returnValue

@app.register('com.myapp.add2')
def add2(a, b):
   res = yield stuff(a, b)
   returnValue(res)
Parameters:uri (unicode) – The URI of the procedure to register under.
subscribe(uri=None)[source]

Decorator attaching a function as an event handler.

The first argument of the decorator should be the URI of the topic to subscribe to. If no URI is given, the URI is constructed from the application URI prefix and the Python function name.

If the function yield, it will be assumed that it’s an asynchronous process and inlineCallbacks will be applied to it.

Example:
@app.subscribe('com.myapp.topic1')
def onevent1(x, y):
   print("got event on topic1", x, y)
Parameters:uri (unicode) – The URI of the topic to subscribe to.
signal(name)[source]

Decorator attaching a function as handler for application signals.

Signals are local events triggered internally and exposed to the developer to be able to react to the application lifecycle.

If the function yield, it will be assumed that it’s an asynchronous coroutine and inlineCallbacks will be applied to it.

Current signals :

  • onjoined: Triggered after the application session has joined the

    realm on the router and registered/subscribed all procedures and event handlers that were setup via decorators.

  • onleave: Triggered when the application session leaves the realm.

@app.signal('onjoined')
def _():
   # do after the app has join a realm
Parameters:name (unicode) – The name of the signal to watch.

autobahn.twisted.websocket

class autobahn.twisted.websocket.WebSocketAdapterProtocol[source]

Bases: twisted.internet.protocol.Protocol

Adapter class for Twisted WebSocket client and server protocols.

connectionMade()[source]
connectionLost(reason)[source]
dataReceived(data)[source]
registerProducer(producer, streaming)[source]

Register a Twisted producer with this protocol.

Modes: Hybi, Hixie

Parameters:
  • producer (object) – A Twisted push or pull producer.
  • streaming (bool) – Producer type.
class autobahn.twisted.websocket.WebSocketServerProtocol[source]

Bases: autobahn.twisted.websocket.WebSocketAdapterProtocol, autobahn.websocket.protocol.WebSocketServerProtocol

Base class for Twisted-based WebSocket server protocols.

class autobahn.twisted.websocket.WebSocketClientProtocol[source]

Bases: autobahn.twisted.websocket.WebSocketAdapterProtocol, autobahn.websocket.protocol.WebSocketClientProtocol

Base class for Twisted-based WebSocket client protocols.

class autobahn.twisted.websocket.WebSocketAdapterFactory[source]

Adapter class for Twisted-based WebSocket client and server factories.

class autobahn.twisted.websocket.WebSocketServerFactory(*args, **kwargs)[source]

Bases: autobahn.twisted.websocket.WebSocketAdapterFactory, autobahn.websocket.protocol.WebSocketServerFactory, twisted.internet.protocol.ServerFactory

Base class for Twisted-based WebSocket server factories.

In addition to all arguments to the constructor of autobahn.websocket.protocol.WebSocketServerFactory, you can supply a reactor keyword argument to specify the Twisted reactor to be used.

class autobahn.twisted.websocket.WebSocketClientFactory(*args, **kwargs)[source]

Bases: autobahn.twisted.websocket.WebSocketAdapterFactory, autobahn.websocket.protocol.WebSocketClientFactory, twisted.internet.protocol.ClientFactory

Base class for Twisted-based WebSocket client factories.

In addition to all arguments to the constructor of autobahn.websocket.protocol.WebSocketClientFactory, you can supply a reactor keyword argument to specify the Twisted reactor to be used.

class autobahn.twisted.websocket.WrappingWebSocketAdapter[source]

An adapter for stream-based transport over WebSocket.

This follows websockify and should be compatible with that.

It uses WebSocket subprotocol negotiation and supports the following WebSocket subprotocols:

  • binary (or a compatible subprotocol)
  • base64

Octets are either transmitted as the payload of WebSocket binary messages when using the binary subprotocol (or an alternative binary compatible subprotocol), or encoded with Base64 and then transmitted as the payload of WebSocket text messages when using the base64 subprotocol.

onConnect(requestOrResponse)[source]
onOpen()[source]
onMessage(payload, isBinary)[source]
onClose(wasClean, code, reason)[source]
write(data)[source]
writeSequence(data)[source]
loseConnection()[source]
getPeer()[source]
getHost()[source]
class autobahn.twisted.websocket.WrappingWebSocketServerProtocol[source]

Bases: autobahn.twisted.websocket.WrappingWebSocketAdapter, autobahn.twisted.websocket.WebSocketServerProtocol

Server protocol for stream-based transport over WebSocket.

class autobahn.twisted.websocket.WrappingWebSocketClientProtocol[source]

Bases: autobahn.twisted.websocket.WrappingWebSocketAdapter, autobahn.twisted.websocket.WebSocketClientProtocol

Client protocol for stream-based transport over WebSocket.

class autobahn.twisted.websocket.WrappingWebSocketServerFactory(factory, url, reactor=None, enableCompression=True, autoFragmentSize=0, subprotocol=None, debug=False)[source]

Bases: autobahn.twisted.websocket.WebSocketServerFactory

Wrapping server factory for stream-based transport over WebSocket.

Parameters:
  • factory (A subclass of twisted.internet.protocol.Factory) – Stream-based factory to be wrapped.
  • url (unicode) – WebSocket URL of the server this server factory will work for.
buildProtocol(addr)[source]
startFactory()[source]
stopFactory()[source]
class autobahn.twisted.websocket.WrappingWebSocketClientFactory(factory, url, reactor=None, enableCompression=True, autoFragmentSize=0, subprotocol=None, debug=False)[source]

Bases: autobahn.twisted.websocket.WebSocketClientFactory

Wrapping client factory for stream-based transport over WebSocket.

Parameters:
  • factory (A subclass of twisted.internet.protocol.Factory) – Stream-based factory to be wrapped.
  • url (unicode) – WebSocket URL of the server this client factory will connect to.
buildProtocol(addr)[source]
autobahn.twisted.websocket.connectWS(factory, contextFactory=None, timeout=30, bindAddress=None)[source]

Establish WebSocket connection to a server. The connection parameters like target host, port, resource and others are provided via the factory.

Parameters:
  • factory (An autobahn.websocket.WebSocketClientFactory instance.) – The WebSocket protocol factory to be used for creating client protocol instances.
  • contextFactory (A twisted.internet.ssl.ClientContextFactory instance.) – SSL context factory, required for secure WebSocket connections (“wss”).
  • timeout (int) – Number of seconds to wait before assuming the connection has failed.
  • bindAddress (tuple) – A (host, port) tuple of local address to bind to, or None.
Returns:

The connector.

Return type:

An object which implements twisted.interface.IConnector.

autobahn.twisted.websocket.listenWS(factory, contextFactory=None, backlog=50, interface='')[source]

Listen for incoming WebSocket connections from clients. The connection parameters like listening port and others are provided via the factory.

Parameters:
  • factory (An autobahn.websocket.WebSocketServerFactory instance.) – The WebSocket protocol factory to be used for creating server protocol instances.
  • contextFactory (A twisted.internet.ssl.ContextFactory.) – SSL context factory, required for secure WebSocket connections (“wss”).
  • backlog (int) – Size of the listen queue.
  • interface (str) – The interface (derived from hostname given) to bind to, defaults to ‘’ (all).
Returns:

The listening port.

Return type:

An object that implements twisted.interface.IListeningPort.

class autobahn.twisted.websocket.WampWebSocketServerProtocol[source]

Bases: autobahn.wamp.websocket.WampWebSocketServerProtocol, autobahn.twisted.websocket.WebSocketServerProtocol

Base class for Twisted-based WAMP-over-WebSocket server protocols.

class autobahn.twisted.websocket.WampWebSocketServerFactory(factory, *args, **kwargs)[source]

Bases: autobahn.wamp.websocket.WampWebSocketServerFactory, autobahn.twisted.websocket.WebSocketServerFactory

Base class for Twisted-based WAMP-over-WebSocket server factories.

protocol

alias of WampWebSocketServerProtocol

class autobahn.twisted.websocket.WampWebSocketClientProtocol[source]

Bases: autobahn.wamp.websocket.WampWebSocketClientProtocol, autobahn.twisted.websocket.WebSocketClientProtocol

Base class for Twisted-based WAMP-over-WebSocket client protocols.

class autobahn.twisted.websocket.WampWebSocketClientFactory(factory, *args, **kwargs)[source]

Bases: autobahn.wamp.websocket.WampWebSocketClientFactory, autobahn.twisted.websocket.WebSocketClientFactory

Base class for Twisted-based WAMP-over-WebSocket client factories.

protocol

alias of WampWebSocketClientProtocol

Module contents

Reactive Manifesto: We are reactive banner