Module autobahn.twisted

Autobahn Twisted specific classes. These are used when Twisted is run as the underlying networking framework.

Component

The component API provides a high-level funcional style method of defining and running WAMP components including authentication configuration

class autobahn.twisted.component.Component(main=None, transports=None, config=None, realm='realm1', extra=None, authentication=None, session_factory=None, is_fatal=None)[source]

A component establishes a transport and attached a session to a realm using the transport for communication.

The transports a component tries to use can be configured, as well as the auto-reconnect strategy.

Parameters:
  • main (callable taking two args reactor and ISession) – After a transport has been connected and a session has been established and joined to a realm, this (async) procedure will be run until it finishes – which signals that the component has run to completion. In this case, it usually doesn’t make sense to use the on_* kwargs. If you do not pass a main() procedure, the session will not be closed (unless you arrange for .leave() to be called).

  • transports (None or str or list) –

    Transport configurations for creating transports. Each transport can be a WAMP URL, or a dict containing the following configuration keys:

    • type (optional): websocket (default) or rawsocket

    • url: the router URL

    • endpoint (optional, derived from URL if not provided):
      • type: “tcp” or “unix”

      • host, port: only for TCP

      • path: only for unix

      • timeout: in seconds

      • tls: True or (under Twisted) an twisted.internet.ssl.IOpenSSLClientComponentCreator instance (such as returned from twisted.internet.ssl.optionsForClientTLS) or CertificateOptions instance.

    • max_retries: Maximum number of reconnection attempts. Unlimited if set to -1.

    • initial_retry_delay: Initial delay for reconnection attempt in seconds (Default: 1.0s).

    • max_retry_delay: Maximum delay for reconnection attempts in seconds (Default: 60s).

    • retry_delay_growth: The growth factor applied to the retry delay between reconnection attempts (Default 1.5).

    • retry_delay_jitter: A 0-argument callable that introduces nose into the delay. (Default random.random)

    • serializer (only for raw socket): Specify an accepted serializer (e.g. ‘json’, ‘msgpack’, ‘cbor’, ‘ubjson’, ‘flatbuffers’)

    • serializers: Specify list of accepted serializers

    • options: tbd

    • proxy: tbd

  • realm (str) – the realm to join

  • authentication (dict) – configuration of authenticators

  • session_factory – if None, ApplicationSession is used, otherwise a callable taking a single config argument that is used to create a new ApplicationSession instance.

  • is_fatal – a callable taking a single argument, an Exception instance. The callable should return True if this error is “fatal”, meaning we should not try connecting to the current transport again. The default behavior (on None) is to always return False

session_factory

The factory of the session we will instantiate.

alias of Session

start(reactor=None)[source]

This starts the Component, which means it will start connecting (and re-connecting) to its configured transports. A Component runs until it is “done”, which means one of: - There was a “main” function defined, and it completed successfully; - Something called .leave() on our session, and we left successfully; - .stop() was called, and completed successfully; - none of our transports were able to connect successfully (failure);

Returns:

a Deferred that fires (with None) when we are “done” or with a Failure if something went wrong.

autobahn.twisted.component.run(components: List[Component], log_level: str = 'info', stop_at_close: bool = True)[source]

High-level API to run a series of components.

This will only return once all the components have stopped (including, possibly, after all re-connections have failed if you have re-connections enabled). Under the hood, this calls twisted.internet.reactor.run() – if you wish to manage the reactor loop yourself, use the autobahn.twisted.component.Component.start() method to start each component yourself.

Parameters:
  • components – the Component(s) you wish to run

  • log_level – a valid log-level (or None to avoid calling start_logging)

  • stop_at_close – Flag to control whether to stop the reactor when done.

WebSocket Protocols and Factories

Classes for WebSocket clients and servers using Twisted.

class autobahn.twisted.websocket.WebSocketServerProtocol[source]

Base class for Twisted-based WebSocket server protocols.

Implements autobahn.websocket.interfaces.IWebSocketChannel.

class autobahn.twisted.websocket.WebSocketClientProtocol[source]

Base class for Twisted-based WebSocket client protocols.

Implements autobahn.websocket.interfaces.IWebSocketChannel.

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

Base class for Twisted-based WebSocket server factories.

Implements autobahn.websocket.interfaces.IWebSocketServerChannelFactory

Note

In addition to all arguments to the constructor of autobahn.websocket.interfaces.IWebSocketServerChannelFactory(), you can supply a reactor keyword argument to specify the Twisted reactor to be used.

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

Base class for Twisted-based WebSocket client factories.

Implements autobahn.websocket.interfaces.IWebSocketClientChannelFactory

Note

In addition to all arguments to the constructor of autobahn.websocket.interfaces.IWebSocketClientChannelFactory(), you can supply a reactor keyword argument to specify the Twisted reactor to be used.

WAMP-over-WebSocket Protocols and Factories

Classes for WAMP-WebSocket clients and servers using Twisted.

class autobahn.twisted.websocket.WampWebSocketServerProtocol[source]

Twisted-based WAMP-over-WebSocket server protocol.

Implements:

class autobahn.twisted.websocket.WampWebSocketClientProtocol[source]

Twisted-based WAMP-over-WebSocket client protocol.

Implements:

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

Twisted-based WAMP-over-WebSocket server protocol factory.

Parameters:
protocol

alias of WampWebSocketServerProtocol

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

Twisted-based WAMP-over-WebSocket client protocol factory.

Parameters:
protocol

alias of WampWebSocketClientProtocol

WAMP-over-RawSocket Protocols and Factories

Classes for WAMP-RawSocket clients and servers using Twisted.

class autobahn.twisted.rawsocket.WampRawSocketServerProtocol[source]

Twisted-based WAMP-over-RawSocket server protocol.

Implements:

dataReceived(data)[source]

Convert int prefixed strings into calls to stringReceived.

class autobahn.twisted.rawsocket.WampRawSocketClientProtocol[source]

Twisted-based WAMP-over-RawSocket client protocol.

Implements:

connectionMade()[source]

Called when a connection is made.

This may be considered the initializer of the protocol, because it is called when the connection is completed. For clients, this is called once the connection to the server has been established; for servers, this is called after an accept() call stops blocking and a socket has been received. If you need to send any greeting or initial message, do it here.

dataReceived(data)[source]

Convert int prefixed strings into calls to stringReceived.

class autobahn.twisted.rawsocket.WampRawSocketServerFactory(factory, serializers=None)[source]

Twisted-based WAMP-over-RawSocket server protocol factory.

Parameters:
protocol

alias of WampRawSocketServerProtocol

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

Twisted-based WAMP-over-RawSocket client protocol factory.

Parameters:
protocol

alias of WampRawSocketClientProtocol

WAMP Sessions

Classes for WAMP sessions using Twisted.

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

WAMP application session for Twisted-based applications.

Implements:

Implements autobahn.wamp.interfaces.ISession()

class autobahn.twisted.wamp.ApplicationRunner(url: str, realm: str | None = None, extra: Dict[str, Any] | None = None, serializers: List[ISerializer] | None = None, ssl: OpenSSLCertificateOptions | None = None, proxy: Dict[str, Any] | None = None, headers: Dict[str, Any] | None = None, websocket_options: Dict[str, Any] | None = None, max_retries: int | None = None, initial_retry_delay: float | None = None, max_retry_delay: float | None = None, retry_delay_growth: float | None = None, retry_delay_jitter: float | None = None)[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 – The WebSocket URL of the WAMP router to connect to (e.g. ws://example.com:8080/mypath)

  • realm – The WAMP realm to join the application session to.

  • extra – Optional extra configuration to forward to the application component.

  • serializers (list) – A list of WAMP serializers to use (or None for default serializers). Serializers must implement autobahn.wamp.interfaces.ISerializer.

  • ssl – (Optional). If specified this should be an instance suitable to pass as sslContextFactory to twisted.internet.endpoints.SSL4ClientEndpoint` such as twisted.internet.ssl.CertificateOptions. Leaving it as None will use the result of calling Twisted twisted.internet.ssl.platformTrust() which tries to use your distribution’s CA certificates.

  • proxy – Explicit proxy server to use; a dict with host and port keys.

  • headers – Additional headers to send (only applies to WAMP-over-WebSocket).

  • websocket_options – Specific WebSocket options to set (only applies to WAMP-over-WebSocket). If not provided, conservative and practical default are chosen.

  • max_retries – Maximum number of reconnection attempts. Unlimited if set to -1.

  • initial_retry_delay – Initial delay for reconnection attempt in seconds (Default: 1.0s).

  • max_retry_delay – Maximum delay for reconnection attempts in seconds (Default: 60s).

  • retry_delay_growth – The growth factor applied to the retry delay between reconnection attempts (Default 1.5).

  • retry_delay_jitter – A 0-argument callable that introduces noise into the delay (Default random.random).

run(make, start_reactor: bool = True, auto_reconnect: bool = False, log_level: str = 'info', endpoint: <InterfaceClass twisted.internet.interfaces.IStreamClientEndpoint> | None = None, reactor: <InterfaceClass twisted.internet.interfaces.IReactorCore> | None = None) None | Deferred[source]

Run the application component.

Parameters:
  • make – A factory that produces instances of autobahn.twisted.wamp.ApplicationSession when called with an instance of autobahn.wamp.types.ComponentConfig.

  • start_reactor – When True (the default) this method starts the Twisted reactor and doesn’t return until the reactor stops. If there are any problems starting the reactor or connect()-ing, we stop the reactor and raise the exception back to the caller.

  • auto_reconnect

  • log_level

  • endpoint

  • reactor

Returns:

None is returned, unless you specify start_reactor=False in which case the Deferred that connect() returns is returned; this will callback() with an IProtocol instance, which will actually be an instance of WampWebSocketClientProtocol

stop()[source]

Stop reconnecting, if auto-reconnecting was enabled.