API Reference

Client

aiowamp is a client library for the WAMP protocol.

exception aiowamp.AbortError(msg)[source]

Join abort error.

Parameters:msg (Abort) –
__init__(msg)[source]

Initialize self. See help(type(self)) for accurate signature.

Parameters:msg (Abort) –
Return type:None
__str__()[source]

Return str(self).

Return type:str
exception aiowamp.AuthError[source]
class aiowamp.AuthKeyring(*methods, auth_id=None)[source]

Initialise the keyring.

Parameters:
  • *methods – Methods to initialise the keyring with.
  • auth_id (Optional[str]) – Auth id to use. Defaults to None.
  • methods (ForwardRef) –
Raises:

ValueError – - The same auth method type was specified multiple times. - No auth id was specified but one of the methods requires it. - Multiple methods specify the same auth extra key with

differing values.

__init__(*methods, auth_id=None)[source]

Initialise the keyring.

Parameters:
  • *methods – Methods to initialise the keyring with.
  • auth_id (Optional[str]) – Auth id to use. Defaults to None.
  • methods (ForwardRef) –
Raises:

ValueError – - The same auth method type was specified multiple times. - No auth id was specified but one of the methods requires it. - Multiple methods specify the same auth extra key with

differing values.

Return type:

None

__repr__()[source]

Return repr(self).

Return type:str
__getitem__(method)[source]

Get the auth method with the given name.

Parameters:method (str) – Name of the method to get.
Return type:AuthMethodABC
Returns:Auth method stored in the keyring.
Raises:KeyError – If no auth method with the given method exists in the keyring.
__len__()[source]

Get the amount of auth methods in the keyring.

Return type:int
__iter__()[source]

Get an iterator for the auth method names in the keyring.

Return type:Iterator[str]
auth_id

Auth id to use during authentication.

Because most authentication methods require an auth id, this is handled by the keyring.

Return type:Optional[str]
auth_extra

Auth extras with all the auth extras from the underlying methods.

None if no auth extras are required.

Return type:Optional[Dict[str, ForwardRef]]
class aiowamp.AuthKeyringABC[source]

Abstract keyring for auth methods.

__str__()[source]

Return str(self).

Return type:str
__getitem__(method)[source]

Get the auth method with the given name.

Parameters:method (str) – Name of the method to get.
Return type:AuthMethodABC
Returns:Auth method stored in the keyring.
Raises:KeyError – If no auth method with the given method exists in the keyring.
__len__()[source]

Get the amount of auth methods in the keyring.

Return type:int
__iter__()[source]

Get an iterator for the auth method names in the keyring.

Return type:Iterator[str]
auth_id

Auth id to use during authentication.

Because most authentication methods require an auth id, this is handled by the keyring.

Return type:Optional[str]
auth_extra

Auth extras with all the auth extras from the underlying methods.

None if no auth extras are required.

Return type:Optional[Dict[str, ForwardRef]]
class aiowamp.AuthMethodABC[source]

Abstract auth method.

method_name = None

Name of the auth method.

__str__()[source]

Return str(self).

Return type:str
requires_auth_id

Whether the auth method requires auth_id to be set.

Return type:bool
auth_extra

Additional auth extras that need to be passed along.

None indicates that no extras need to be passed.

Return type:Optional[Dict[str, ForwardRef]]
authenticate(challenge)[source]

Generate an authenticate message for the challenge.

Parameters:challenge (Challenge) – Challenge message to respond to.
Return type:Union[Authenticate, Abort]
Returns:Either an authenticate message to send to the router or an abort message to indicate that the attempt should be aborted.
Raises:Exception – When something goes wrong during authentication. Should be interpreted the same as an abort message.
check_welcome(welcome)[source]

Check the welcome message sent by the router.

Used to perform mutual authentication.

Parameters:welcome (Welcome) – Welcome message sent by the router.
Raises:aiowamp.AuthError
Return type:None
exception aiowamp.BaseError[source]

Base exception for all WAMP related errors.

You will most likely never encounter this error directly, but its subclasses.

class aiowamp.BlackWhiteList(*, excluded_ids=None, excluded_auth_ids=None, excluded_auth_roles=None, eligible_ids=None, eligible_auth_ids=None, eligible_auth_roles=None)[source]

Data type for black- and whitelisting subscribers.

BlackWhiteList is quite a mouthful, so let’s use bwlist for short.

If both exclusion and eligible rules are present, the Broker will dispatch events published only to Subscribers that are not explicitly excluded and which are explicitly eligible.

Like list, an empty bwlist is falsy (i.e. bool(BlackWhiteList()) is False).

bwlist is also a container (i.e. support x in bwlist), it returns whether the given key will receive the event with the current constraints.

bwlist will keep the constraint lists in ascending order.

Notes

bwlist assumes that the set of auth ids is distinct from the set of auth roles. If they are not, the checks may return invalid results.

Parameters:

Create a new bwlist.

The given iterables are converted into lists, sorted, and duplicates are removed.

Parameters:
__init__(*, excluded_ids=None, excluded_auth_ids=None, excluded_auth_roles=None, eligible_ids=None, eligible_auth_ids=None, eligible_auth_roles=None)[source]

Create a new bwlist.

The given iterables are converted into lists, sorted, and duplicates are removed.

Parameters:
Return type:

None

excluded_ids

Excluded session ids.

Only subscribers whose session id IS NOT in this list will receive the event.

excluded_auth_ids

Excluded auth ids.

excluded_auth_roles

Excluded auth roles.

eligible_ids

Eligible session ids.

Only subscribers whose session id IS in this list will receive the event.

eligible_auth_ids

Eligible auth ids.

eligible_auth_roles

Eligible auth roles.

__str__()[source]

Return str(self).

Return type:str
__bool__()[source]

Check if the bwlist contains any constraints.

Return type:bool
__contains__(receiver)[source]

Check if the receiver would receive the event.

Parameters:receiver (Any) – Session id, auth id, or auth role to check.
Return type:bool
Returns:True if the receiver is eligible and not excluded, False otherwise.
is_excluded(receiver)[source]

Check if the receiver is excluded.

Parameters:receiver (Union[int, str]) – Session id, auth id, or auth role to check.
Return type:bool
Returns:True if there is an exclusion list and the receiver is in it, False otherwise.
is_eligible(receiver)[source]

Check if the receiver is eligible.

Parameters:receiver (Union[int, str]) – Session id, auth id, or auth role to check.
Return type:bool
Returns:True if there is no eligible list or the receiver is in it, False otherwise.
exclude_session_id(session_id)[source]

Add an id to the excluded session ids.

Parameters:session_id (int) – Session id to add.
Return type:None
exclude_auth_id(auth_id)[source]

Add an id to the excluded auth ids.

Parameters:auth_id (str) – Auth id to add.
Return type:None
exclude_auth_role(auth_role)[source]

Add a role to the excluded auth roles.

Parameters:auth_role (str) – Auth role to add.
Return type:None
unexclude(receiver)[source]

Remove a receiver from the excluded receivers.

This is the reverse operations for the “exclude_” methods.

Parameters:receiver (Union[int, str]) – Receiver to remove.
Raises:ValueError – If the receiver isn’t excluded.
Return type:None
allow_session_id(session_id)[source]

Add an id to the eligible ids.

Parameters:session_id (int) – Session id to add
Return type:None
allow_auth_id(auth_id)[source]

Add an id to the eligible auth ids.

Parameters:auth_id (str) – Auth id to add.
Return type:None
allow_auth_role(auth_role)[source]

Add a role to the eligible auth roles.

Parameters:auth_role (str) – Auth role to add.
Return type:None
disallow(receiver)[source]

Remove a receiver from the eligible receivers.

This is the reverse operation for the “allow_” methods.

Parameters:receiver (Union[int, str]) – Receiver to remove.
Raises:ValueError – If the receiver isn’t eligible.
Return type:None
to_options(options=None)[source]

Convert the bwlist to WAMP options.

Parameters:options (Optional[Dict[str, ForwardRef]]) – Dict to write the options to. If not specified, a dict will be created,
Return type:Dict[str, ForwardRef]
Returns:WAMP dict containing the constraints from the bwlist. If an argument for options was passed, the return value will be the same instance.
classmethod from_options(options)[source]

Create a bwlist from WAMP options.

Parameters:
Return type:

~T

Returns:

New bwlist with the constraints from the options.

class aiowamp.CRAuth(secret)[source]

Auth method for challenge response authentication.

WAMP Challenge-Response (“WAMP-CRA”) authentication is a simple, secure authentication mechanism using a shared secret. The client and the server share a secret. The secret never travels the wire, hence WAMP-CRA can be used via non-TLS connections. The actual pre-sharing of the secret is outside the scope of the authentication mechanism.

Parameters:secret (str) –

Initialise the auth method.

Parameters:secret (str) – Secret to use.
__init__(secret)[source]

Initialise the auth method.

Parameters:secret (str) – Secret to use.
Return type:None
__repr__()[source]

Return repr(self).

Return type:str
requires_auth_id

Whether the auth method requires auth_id to be set.

Return type:bool
auth_extra

Additional auth extras that need to be passed along.

None indicates that no extras need to be passed.

Return type:None
pbkdf2_hmac(salt, key_len, iterations)[source]

Derive the token using the pdkdf2 scheme.

Parameters:
  • salt (str) – Salt
  • key_len (int) – Key length
  • iterations (int) – Amount of iterations
Return type:

bytes

Returns:

Generated token bytes.

secret

Secret to use for authentication.

authenticate(challenge)[source]

Generate an authenticate message for the challenge.

Parameters:challenge (Challenge) – Challenge message to respond to.
Return type:Authenticate
Returns:Either an authenticate message to send to the router or an abort message to indicate that the attempt should be aborted.
Raises:Exception – When something goes wrong during authentication. Should be interpreted the same as an abort message.
class aiowamp.Call(session, call, *, cancel_mode)[source]

Initialise the call.

Note that you normally shouldn’t create an instance yourself, it doesn’t actively listen to incoming messages. It expects relevant messages to be passed to handle_response.

Parameters:
  • session (SessionABC) – Session to use to send messages.
  • call (Call) – Call message that spawned the call.
  • cancel_mode (NewType()(CancelMode, str)) – Cancel mode used when cancelling the call.
__init__(session, call, *, cancel_mode)[source]

Initialise the call.

Note that you normally shouldn’t create an instance yourself, it doesn’t actively listen to incoming messages. It expects relevant messages to be passed to handle_response.

Parameters:
  • session (SessionABC) – Session to use to send messages.
  • call (Call) – Call message that spawned the call.
  • cancel_mode (NewType()(CancelMode, str)) – Cancel mode used when cancelling the call.
Return type:

None

session

Session used to send messages.

__repr__()[source]

Return repr(self).

Return type:str
request_id

Request id of the call.

Return type:int
done

Whether the call is complete.

Return type:bool
cancelled

Whether the call has been cancelled.

Return type:bool
on_progress(handler)[source]

Add a progress handler.

Parameters:handler (Callable[[ForwardRef], Union[Any, Awaitable[Any]]]) – Handler to call with the progress results.
Return type:None
cancel(cancel_mode=None, *, options=None)[source]

Cancel the call.

Parameters:
Return type:

None

kill(e)[source]

Kill the call.

Parameters:e (Exception) – Exception to raise when interacting with the call.
Return type:None
next_progress()[source]

Get the next progress result.

Return type:Optional[InvocationProgress]
Returns:The next progress result, or None if the call is done.
result()[source]

Get the result of the call.

Return type:InvocationResult
handle_response(msg)[source]

Handle a message targeted to this call.

Parameters:msg (MessageABC) – Message received in relation to this call.
Return type:bool
class aiowamp.CallABC[source]

Represents an ongoing call of a remote procedure.

__str__()[source]

Return str(self).

Return type:str
__await__()[source]

Wait for the result of the call.

This is the same as result.

Returns:An awaitable containing the result.
request_id

Request id of the call.

Return type:int
done

Whether the call is complete.

Return type:bool
cancelled

Whether the call has been cancelled.

Return type:bool
on_progress(handler)[source]

Add a progress handler.

Parameters:handler (Callable[[ForwardRef], Union[Any, Awaitable[Any]]]) – Handler to call with the progress results.
Return type:None
__anext__()[source]

Wait for the next progress result.

Returns:Next progress result.
Raises:StopAsyncIteration – If the call has completed.
cancel(cancel_mode=None, *, options=None)[source]

Cancel the call.

Parameters:
Return type:

None

next_progress()[source]

Get the next progress result.

Return type:Optional[InvocationProgress]
Returns:The next progress result, or None if the call is done.
result()[source]

Get the result of the call.

Return type:InvocationResult
class aiowamp.Client(session)[source]

Initialise the client.

A client is just a wrapper for a session. It takes full control over the session, so when the client closes so will the session.

Parameters:session (SessionABC) – Session to wrap.
__init__(session)[source]

Initialise the client.

A client is just a wrapper for a session. It takes full control over the session, so when the client closes so will the session.

Parameters:session (SessionABC) – Session to wrap.
Return type:None
session

Session the client is attached to.

id_gen

ID generator used to generate the client ids.

__repr__()[source]

Return repr(self).

Return type:str
__str__()[source]

Return str(self).

Return type:str
close(details=None, *, reason=None)[source]

Close the client and the underlying session.

Parameters:
  • details (Optional[Dict[str, ForwardRef]]) – Additional details to send with the close message.
  • reason (Optional[str]) – URI denoting the reason for closing. Defaults to aiowamp.uri.CLOSE_NORMAL.
Return type:

None

publish(topic, *args, kwargs=None, acknowledge=None, blackwhitelist=None, exclude_me=None, disclose_me=None, resource_key=None, options=None)[source]

Publish an event to a topic.

Parameters:
Return type:

None

register(procedure, handler, *, disclose_caller=None, match_policy=None, invocation_policy=None, options=None)[source]

Register a procedure.

Parameters:
Return type:

int

Returns:

The registration id of the registered procedure. Can be used to unregister the procedure.

subscribe(topic, callback, *, match_policy=None, node_key=None, options=None)[source]

Subscribe to a topic.

Parameters:
Return type:

int

unregister(procedure, registration_id=None)[source]

Unregister a procedure.

Parameters:
  • procedure (str) – Procedure uri to unregister.
  • registration_id (Optional[int]) – Specific registration id to unregister. If not specified, ALL registrations for the procedure will be unregistered.
Raises:

KeyError – If no registration for the procedure exists.

Return type:

None

unsubscribe(topic, subscription_id=None)[source]

Unsubscribe from the given topic.

Parameters:
  • topic (str) – Topic URI to unsubscribe from.
  • subscription_id (Optional[int]) – Specific subscription id to unsubscribe. If None, unsubscribe all subscriptions to the topic.
Raises:

KeyError – If not subscribed to the topic.

Return type:

None

wait_until_done()[source]

Wait until the client is done.

Return type:None
get_registration_ids(procedure)[source]

Get the ids of the registrations for the given procedure.

Parameters:procedure (str) – Procedure to get registration ids for.
Return type:Tuple[int, …]
Returns:Tuple containing the registration ids.
call(procedure, *args, kwargs=None, receive_progress=None, call_timeout=None, cancel_mode=None, disclose_me=None, resource_key=None, options=None)[source]

Call a remote procedure.

Parameters:
Return type:

CallABC

Returns:

The call instance to interact with the call.

get_subscription_ids(topic)[source]

Get the ids of the subscriptions for the given topic.

Parameters:topic (str) – Topic to get subscription ids for.
Return type:Tuple[int, …]
Returns:Tuple of subscription ids.
class aiowamp.ClientABC[source]

WAMP Client.

Implements the publisher, subscriber, caller, and callee roles.

__str__()[source]

Return str(self).

Return type:str
call(procedure, *args, kwargs=None, receive_progress=None, call_timeout=None, cancel_mode=None, disclose_me=None, resource_key=None, options=None)[source]

Call a remote procedure.

Parameters:
Return type:

CallABC

Returns:

The call instance to interact with the call.

close(details=None, *, reason=None)[source]

Close the client and the underlying session.

Parameters:
  • details (Optional[Dict[str, ForwardRef]]) – Additional details to send with the close message.
  • reason (Optional[str]) – URI denoting the reason for closing. Defaults to aiowamp.uri.CLOSE_NORMAL.
Return type:

None

publish(topic, *args, kwargs=None, acknowledge=None, blackwhitelist=None, exclude_me=None, disclose_me=None, resource_key=None, options=None)[source]

Publish an event to a topic.

Parameters:
Return type:

None

register(procedure, handler, *, disclose_caller=None, match_policy=None, invocation_policy=None, options=None)[source]

Register a procedure.

Parameters:
Return type:

int

Returns:

The registration id of the registered procedure. Can be used to unregister the procedure.

subscribe(topic, callback, *, match_policy=None, node_key=None, options=None)[source]

Subscribe to a topic.

Parameters:
Return type:

int

unregister(procedure, registration_id=None)[source]

Unregister a procedure.

Parameters:
  • procedure (str) – Procedure uri to unregister.
  • registration_id (Optional[int]) – Specific registration id to unregister. If not specified, ALL registrations for the procedure will be unregistered.
Raises:

KeyError – If no registration for the procedure exists.

Return type:

None

unsubscribe(topic, subscription_id=None)[source]

Unsubscribe from the given topic.

Parameters:
  • topic (str) – Topic URI to unsubscribe from.
  • subscription_id (Optional[int]) – Specific subscription id to unsubscribe. If None, unsubscribe all subscriptions to the topic.
Raises:

KeyError – If not subscribed to the topic.

Return type:

None

wait_until_done()[source]

Wait until the client is done.

Return type:None
exception aiowamp.ClientClosed[source]
class aiowamp.CommonTransportConfig(url, serializer=None, ssl_context=None)[source]

Transport configuration used by transport factories.

Parameters:
  • url (urlparse.ParseResult) –
  • serializer (Optional['aiowamp.SerializerABC']) –
  • ssl_context (Optional[ssl.SSLContext]) –
url = None

URL to connect to.

serializer = None

Serializer to use.

If None a sensible default will be used.

ssl_context = None

SSL options.

If None, TLS will still be used if the url specifies a secure scheme (ex: “wss”).

__weakref__

list of weak references to the object (if defined)

exception aiowamp.ErrorResponse(message)[source]
Parameters:message (Error) –
__init__(message)[source]

Initialize self. See help(type(self)) for accurate signature.

Parameters:message (Error) –
message

Error message.

__repr__()[source]

Return repr(self).

Return type:str
__str__()[source]

Return str(self).

Return type:str
class aiowamp.IDGenerator[source]

Sequential ID generator.

Generates sequential ids starting from 1 up to 2^53 (inclusive) before restarting.

Create a new id generator.

The first generated id will be 1.

__init__()[source]

Create a new id generator.

The first generated id will be 1.

Return type:None
__repr__()[source]

Return repr(self).

Return type:str
__str__()[source]

Return str(self).

Return type:str
__next__()[source]

Generate the next id.

Return type:int
Returns:The generated id.
class aiowamp.IDGeneratorABC[source]

Abstract WAMP ID generator type.

Should be used like an iterator by passing it to next. Note that the generator should never raise StopIteration.

__str__()[source]

Return str(self).

Return type:str
__next__()[source]

Generate the next id.

Return type:int
Returns:The generated id.
exception aiowamp.Interrupt(options)[source]
Parameters:options (Dict[str, ForwardRef]) –
__init__(options)[source]

Initialize self. See help(type(self)) for accurate signature.

Parameters:options (Dict[str, ForwardRef]) –
Return type:None
options

Options sent with the interrupt.

__repr__()[source]

Return repr(self).

Return type:str
cancel_mode

Cancel mode sent with the interrupt.

exception aiowamp.InvalidMessage[source]

Exception for invalid messages.

class aiowamp.Invocation(session, client, msg, *, procedure)[source]

Create a new invocation instance.

Normally you should not create these yourself, they don’t actively listen for incoming messages. Instead, they rely on the aiowamp.ClientABC to receive and pass them.

Parameters:
  • session (SessionABC) – WAMP Session to send messages in.
  • msg (Invocation) – Invocation message that spawned the invocation.
  • procedure (URI) – Registered procedure URI.
  • client (~ClientT) –
__init__(session, client, msg, *, procedure)[source]

Create a new invocation instance.

Normally you should not create these yourself, they don’t actively listen for incoming messages. Instead, they rely on the aiowamp.ClientABC to receive and pass them.

Parameters:
  • session (SessionABC) – WAMP Session to send messages in.
  • msg (Invocation) – Invocation message that spawned the invocation.
  • procedure (URI) – Registered procedure URI.
  • client (~ClientT) –
Return type:

None

session

Session used to send messages.

__getitem__(key)[source]

Get a value from the arguments or keyword arguments.

Parameters:key (Union[int, str]) – Key to get value for. If the key is a string, the value is looked up in the keyword arguments. Integers are treated as indices to the arguments.
Return type:Union[int, str, bool, ForwardRef, ForwardRef]
Returns:Value for the given key.
Raises:LookupError – If the key doesn’t exist.
client

Underlying client that received the invocation.

Return type:~ClientT
request_id

ID of the invocation.

Return type:int
registered_procedure

URI that was used to register the procedure.

See procedure for the uri that was called.

Return type:URI
args

Call arguments.

Return type:Tuple[Union[int, str, bool, ForwardRef, ForwardRef], …]
kwargs

Call keyword arguments.

Return type:Dict[str, ForwardRef]
details

Additional call details.

Return type:Dict[str, ForwardRef]
timeout

Timeout in seconds.

0 if no timeout was provided which means the call doesn’t time out.

Return type:float
timeout_at

Time at which the invocation will be cancelled.

None if the call doesn’t time out.

Trying to send a message (result, progress, error) after the call is cancelled will raise an exception. Use done to check whether the invocation can send messages.

Return type:Optional[datetime]
done

Whether the invocation is done.

Return type:bool
interrupt

Interrupt message sent by the caller.

None if the message hasn’t been interrupted.

Return type:Optional[Interrupt]
send_error(error, *args, kwargs=None, details=None)[source]

Send an error.

This completes the invocation.

Parameters:
Return type:

None

send_progress(*args, kwargs=None, options=None)[source]

Send a progress result.

Use may_send_progress to check whether the caller is willing to receive progress results.

Parameters:
Return type:

None

send_result(*args, kwargs=None, options=None)[source]

Send the final result.

This completes the invocation.

Parameters:
Return type:

None

class aiowamp.InvocationABC[source]

Invocation context passed to a procedure.

__str__()[source]

Return str(self).

Return type:str
client

Underlying client that received the invocation.

Return type:~ClientT
request_id

ID of the invocation.

Return type:int
registered_procedure

URI that was used to register the procedure.

See procedure for the uri that was called.

Return type:URI
procedure

Concrete procedure that caused the invocation.

This will be the same as registered_procedure unless the procedure was registered with a pattern-based matching policy.

Return type:URI
args

Call arguments.

Return type:Tuple[Union[int, str, bool, ForwardRef, ForwardRef], …]
kwargs

Call keyword arguments.

Return type:Dict[str, ForwardRef]
details

Additional call details.

Return type:Dict[str, ForwardRef]
may_send_progress

Whether or not the caller is willing to receive progressive results.

Return type:bool
caller_id

Get the caller’s id.

You can specify the “disclose_caller” option when registering a procedure to force disclosure.

Return type:Optional[int]
Returns:WAMP id of the caller, or None if not specified.
trust_level

Get the router assigned trust level.

The trust level 0 means lowest trust, and higher integers represent (application-defined) higher levels of trust.

Return type:Optional[int]
Returns:The trust level, or None if not specified.
timeout

Timeout in seconds.

0 if no timeout was provided which means the call doesn’t time out.

Return type:float
timeout_at

Time at which the invocation will be cancelled.

None if the call doesn’t time out.

Trying to send a message (result, progress, error) after the call is cancelled will raise an exception. Use done to check whether the invocation can send messages.

Return type:Optional[datetime]
done

Whether the invocation is done.

Return type:bool
interrupt

Interrupt message sent by the caller.

None if the message hasn’t been interrupted.

Return type:Optional[Interrupt]
send_error(error, *args, kwargs=None, details=None)[source]

Send an error.

This completes the invocation.

Parameters:
Return type:

None

send_progress(*args, kwargs=None, options=None)[source]

Send a progress result.

Use may_send_progress to check whether the caller is willing to receive progress results.

Parameters:
Return type:

None

send_result(*args, kwargs=None, options=None)[source]

Send the final result.

This completes the invocation.

Parameters:
Return type:

None

exception aiowamp.InvocationError(uri, *args, kwargs=None, details=None)[source]
Parameters:
__init__(uri, *args, kwargs=None, details=None)[source]

Initialize self. See help(type(self)) for accurate signature.

Parameters:
Return type:

None

__repr__()[source]

Return repr(self).

Return type:str
__str__()[source]

Return str(self).

Return type:str
class aiowamp.InvocationProgress(*args, **kwargs)[source]

Helper class for procedures.

Instances of this class can be yielded by procedures to indicate that it it’s intended to be sent as a progress.

Usually, because there’s no way to tell whether an async generator has yielded for the last time, aiowamp waits for the next yield before sending a progress result (i.e. it always lags behind one message). When returning an instance of this class however, aiowamp will send it immediately.

It is possible to abuse this by returning an instance of this class for the final yield. This is not supported by the WAMP protocol and currently results in aiowamp sending an empty final result.

Parameters:
class aiowamp.InvocationResult(*args, **kwargs)[source]

Helper class for procedures.

Use this to return/yield a result from a aiowamp.InvocationHandler containing keyword arguments.

Parameters:
__init__(*args, **kwargs)[source]

Initialize self. See help(type(self)) for accurate signature.

Parameters:
Return type:

None

args

Arguments.

kwargs

Keyword arguments.

details

Details.

class aiowamp.JSONSerializer(*, decoder=None, encoder=None)[source]

Serializer for the JSON format.

Provides a custom json.JSONDecoder and json.JSONEncoder which handle the special WAMP string format for binary data.

Parameters:
  • decoder (Optional[JSONDecoder]) –
  • encoder (Optional[JSONEncoder]) –
  • decoder – Decoder to be used. Defaults to JSONDecoder which supports binary data in strings.
  • encoder – Encoder to be used. Defaults to JSONEncoder which supports binary data in strings.
__init__(*, decoder=None, encoder=None)[source]
Parameters:
  • decoder (Optional[JSONDecoder]) – Decoder to be used. Defaults to JSONDecoder which supports binary data in strings.
  • encoder (Optional[JSONEncoder]) – Encoder to be used. Defaults to JSONEncoder which supports binary data in strings.
Return type:

None

decoder

JSON decoder used to decode incoming messages.

encoder

JSON encoder used to encode outgoing messages.

serialize(msg)[source]

Serialise a message.

Parameters:msg (MessageABC) – Message to serialise.
Return type:bytes
Returns:bytes representation of the message.
Raises:Exception – If the message couldn’t be serialised.
deserialize(data)[source]

Deserialise the bytes representation of a message.

Parameters:

data (bytes) – bytes representation of a message.

Return type:

MessageABC

Returns:

Deserialised message.

Raises:
class aiowamp.MessageABC[source]

Base class for WAMP messages.

message_type = None

Type code of the message.

__str__()[source]

Return str(self).

Return type:str
to_message_list()[source]

Convert the message to a list

Return type:List[ForwardRef]
Returns:List containing the message including the message type.
classmethod from_message_list(msg_list)[source]

Build the message from msg_list.

Parameters:
  • msg_list (List[ForwardRef]) – Message list without the message type.
  • cls (Type[~T]) –
Return type:

~T

Returns:

Instance of the message type.

class aiowamp.MessagePackSerializer[source]
serialize(msg)[source]

Serialise a message.

Parameters:msg (MessageABC) – Message to serialise.
Return type:bytes
Returns:bytes representation of the message.
Raises:Exception – If the message couldn’t be serialised.
deserialize(data)[source]

Deserialise the bytes representation of a message.

Parameters:

data (bytes) – bytes representation of a message.

Return type:

MessageABC

Returns:

Deserialised message.

Raises:
class aiowamp.RawSocketTransport(reader, writer, serializer, *, recv_limit, send_limit)[source]

WAMP transport over raw sockets.

Notes

The start method needs to be called before recv can read any messages. This is done as part of the perform_client_handshake procedure.

Parameters:
  • reader (StreamReader) –
  • writer (StreamWriter) –
  • serializer (SerializerABC) –
  • recv_limit (int) –
  • send_limit (int) –
  • reader – Reader to read from.
  • writer – Writer to write to.
  • serializer – Serializer to use.
  • recv_limit – Max amount of bytes willing to receive.
  • send_limit – Max amount of bytes remote is willing to receive.

See also

The connect_raw_socket method for opening a connection.

__init__(reader, writer, serializer, *, recv_limit, send_limit)[source]
Parameters:
  • reader (StreamReader) – Reader to read from.
  • writer (StreamWriter) – Writer to write to.
  • serializer (SerializerABC) – Serializer to use.
  • recv_limit (int) – Max amount of bytes willing to receive.
  • send_limit (int) – Max amount of bytes remote is willing to receive.

See also

The connect_raw_socket method for opening a connection.

Return type:None
reader

Reader for the underlying stream.

writer

Writer for the underlying transport.

serializer

Serializer used to serialise messages.

__repr__()[source]

Return repr(self).

Return type:str
open

Whether the transport is open and usable.

Return type:bool
close()[source]

Close the transport.

Return type:None
recv()[source]

Receive a message.

Return type:MessageABC
Returns:Received message.
send(msg)[source]

Send a message.

Parameters:msg (MessageABC) – Message to send.
Return type:None
class aiowamp.SerializerABC[source]

Serializer for messages.

Normally an aiowamp.TransportABC keeps a serializer which it uses.

Deliberately doesn’t adhere to Python’s dump / load interface because the objects in question are always aiowamp.MessageABC and the serialized format is always bytes.

__str__()[source]

Return str(self).

Return type:str
serialize(msg)[source]

Serialise a message.

Parameters:msg (MessageABC) – Message to serialise.
Return type:bytes
Returns:bytes representation of the message.
Raises:Exception – If the message couldn’t be serialised.
deserialize(data)[source]

Deserialise the bytes representation of a message.

Parameters:

data (bytes) – bytes representation of a message.

Return type:

MessageABC

Returns:

Deserialised message.

Raises:
class aiowamp.Session(transport, session_id, realm, details, *, control_transport=True)[source]
Parameters:
__init__(transport, session_id, realm, details, *, control_transport=True)[source]

Initialize self. See help(type(self)) for accurate signature.

Parameters:
Return type:

None

transport

Transport used by the session.

control_transport

Whether the session controls the underlying transport.

If this is True, the session will close the transport when it

__repr__()[source]

Return repr(self).

Return type:str
session_id

Session ID.

Return type:int
realm

Name of the realm the session is attached to.

Return type:str
send(msg)[source]

Send a message using the underlying transport.

Parameters:msg (MessageABC) –
Return type:None
goodbye

Goodbye message sent by the remote.

Return type:Optional[Goodbye]
class aiowamp.SessionABC[source]

Abstract session type.

A Session is a transient conversation between two Peers attached to a Realm and running over a Transport.

__str__()[source]

Return str(self).

Return type:str
session_id

Session ID.

Return type:int
realm

Name of the realm the session is attached to.

Return type:str
goodbye

Goodbye message sent by the remote.

Return type:Optional[Goodbye]
send(msg)[source]

Send a message using the underlying transport.

Parameters:msg (MessageABC) –
Return type:None
class aiowamp.SubscriptionEvent(client, msg, *, topic)[source]

Create a new SubscriptionEven instance.

There shouldn’t be a need to create these yourself, unless you’re creating your own aiowamp.ClientABC. Unlike aiowamp.Invocation it doesn’t require to be managed though.

Parameters:
  • client (~ClientT) – Client used to unsubscribe.
  • msg (Event) – Event message.
  • topic (URI) – Registered topic URI.
__init__(client, msg, *, topic)[source]

Create a new SubscriptionEven instance.

There shouldn’t be a need to create these yourself, unless you’re creating your own aiowamp.ClientABC. Unlike aiowamp.Invocation it doesn’t require to be managed though.

Parameters:
  • client (~ClientT) – Client used to unsubscribe.
  • msg (Event) – Event message.
  • topic (URI) – Registered topic URI.
Return type:

None

client

Underlying client that received the event.

Return type:~ClientT
unsubscribe()[source]

Unsubscribe from the topic.

Return type:None
publication_id

ID of the publication.

Return type:int
subscribed_topic

URI of the subscription.

This is the uri that was passed to the subscribe method.

See topic for the uri that the event was published to.

Return type:URI
args

Event arguments.

Return type:Tuple[Union[int, str, bool, ForwardRef, ForwardRef], …]
kwargs

Event keyword arguments.

Return type:Dict[str, ForwardRef]
details

Additional event details.

Return type:Dict[str, ForwardRef]
class aiowamp.SubscriptionEventABC[source]

Subscription event.

__str__()[source]

Return str(self).

Return type:str
client

Underlying client that received the event.

Return type:~ClientT
publication_id

ID of the publication.

Return type:int
subscribed_topic

URI of the subscription.

This is the uri that was passed to the subscribe method.

See topic for the uri that the event was published to.

Return type:URI
topic

Concrete topic that caused the event.

This will be the same as subscribed_topic unless the handler subscribed with a pattern-based matching policy.

Return type:URI
args

Event arguments.

Return type:Tuple[Union[int, str, bool, ForwardRef, ForwardRef], …]
kwargs

Event keyword arguments.

Return type:Dict[str, ForwardRef]
details

Additional event details.

Return type:Dict[str, ForwardRef]
publisher_id

Get the publisher’s id.

Return type:Optional[int]
Returns:WAMP id of the caller, or None if not disclosed.
trust_level

Get the router assigned trust level.

The trust level 0 means lowest trust, and higher integers represent (application-defined) higher levels of trust.

Return type:Optional[int]
Returns:The trust level, or None if not specified.
unsubscribe()[source]

Unsubscribe from the topic.

Return type:None
class aiowamp.TicketAuth(ticket)[source]

Auth method for ticket-based authentication.

With Ticket-based authentication, the client needs to present the server an authentication “ticket” - some magic value to authenticate itself to the server.

This “ticket” could be a long-lived, pre-agreed secret (e.g. a user password) or a short-lived authentication token (like a Kerberos token). WAMP does not care or interpret the ticket presented by the client.

Caution: This scheme is extremely simple and flexible, but the resulting security may be limited. E.g., the ticket value will be sent over the wire. If the transport WAMP is running over is not encrypted, a man-in-the-middle can sniff and possibly hijack the ticket. If the ticket value is reused, that might enable replay attacks.
Parameters:ticket (str) –
__init__(ticket)[source]

Initialize self. See help(type(self)) for accurate signature.

Parameters:ticket (str) –
Return type:None
authenticate(challenge)[source]

Generate an authenticate message for the challenge.

Parameters:challenge (Challenge) – Challenge message to respond to.
Return type:Authenticate
Returns:Either an authenticate message to send to the router or an abort message to indicate that the attempt should be aborted.
Raises:Exception – When something goes wrong during authentication. Should be interpreted the same as an abort message.
requires_auth_id

Whether the auth method requires auth_id to be set.

Return type:bool
auth_extra

Additional auth extras that need to be passed along.

None indicates that no extras need to be passed.

Return type:None
class aiowamp.TransportABC[source]

Abstract transport type.

A Transport connects two WAMP Peers and provides a channel over which WAMP messages for a WAMP Session can flow in both directions.

WAMP can run over any Transport which is message-based, bidirectional, reliable and ordered.

__str__()[source]

Return str(self).

Return type:str
open

Whether the transport is open and usable.

Return type:bool
close()[source]

Close the transport.

Return type:None
recv()[source]

Receive a message.

Return type:MessageABC
Returns:Received message.
send(msg)[source]

Send a message.

Parameters:msg (MessageABC) – Message to send.
Return type:None
exception aiowamp.TransportError[source]

Transport level error.

class aiowamp.URI[source]

WAMP URI.

A URI is a subclass of str and can be used wherever a string would be expected. Apart from object identity (id) URIs are also completely equal to their string equivalent (ex: “hash(aiowamp.URI(‘a’)) == hash(‘a’)).

The benefit of URIs (apart from the semantics) is that they can carry a MatchPolicy with them. All functions that accept a “match_policy” keyword argument will also check for the match_policy (Note that the keyword argument will always be used if specified).

Create a new uri.

Parameters:
  • uri – URI to set the value to.
  • match_policy – Match policy to use for the URI. Defaults to None.
Returns:

New uri instance.

match_policy

Match policy passed to the instance.

static __new__(cls, uri, *, match_policy=None)[source]

Create a new uri.

Parameters:
  • uri (str) – URI to set the value to.
  • match_policy (Optional[NewType()(MatchPolicy, str)]) – Match policy to use for the URI. Defaults to None.
  • cls (Type[~T]) –
Return type:

~T

Returns:

New uri instance.

classmethod cast(uri)[source]

Cast the string to a uri.

Parameters:
  • uri (str) – URI to cast.
  • cls (Type[~T]) –
Return type:

~T

Returns:

If the uri is already an instance of URI, it is returned directly. Otherwise a new URI is created.

__repr__()[source]

Return repr(self).

Return type:str
classmethod policy_match(policy, uri, other)[source]

Check if a uri matches another based on the policy.

Parameters:
  • policy (NewType()(MatchPolicy, str)) – Matching policy to use.
  • uri (str) – URI to be checked.
  • other (str) – URI to check against (i.e. the pattern).
Return type:

bool

Returns:

Whether the uri matches the pattern “other”.

Raises:

ValueError – If an invalid policy was specified.

static prefix_match(uri, prefix)[source]

Check whether the URI matches the prefix.

Parameters:
  • uri (str) – URI to be checked.
  • prefix (str) – Prefix to check against.
Return type:

bool

Returns:

Whether the URI has the given prefix.

static wildcard_match(uri, wildcard)[source]

Check if the URI matches the wildcard.

Wildcards have empty URI components which can match anything (apart from ‘.’).

Parameters:
  • uri (str) – URI to be checked.
  • wildcard (str) – Wildcard to check against.
Return type:

bool

Returns:

Whether the URI matches the wildcard.

exception aiowamp.UnexpectedMessageError(received, expected)[source]

Exception raised when an unexpected message type is received.

Parameters:
received

Message that was received.

expected

Message type that was expected.

__str__()[source]

Return str(self).

Return type:str
class aiowamp.WebSocketTransport(ws_client, serializer, *, payload_text)[source]

WAMP Transport over web socket.

Parameters:
  • ws_client (MockObject) –
  • serializer (SerializerABC) –
  • payload_text (bool) –
  • ws_client – Connected web socket client to use.
  • serializer – Serializer to use.
  • payload_text – Whether the serialised messages should be sent in a text frame. If False, binary frames are used.
__init__(ws_client, serializer, *, payload_text)[source]
Parameters:
  • ws_client (MockObject) – Connected web socket client to use.
  • serializer (SerializerABC) – Serializer to use.
  • payload_text (bool) – Whether the serialised messages should be sent in a text frame. If False, binary frames are used.
Return type:

None

ws_client

Underlying web socket client.

serializer

Serializer used for the transport.

open

Whether the transport is open and usable.

Return type:bool
close()[source]

Close the transport.

Return type:None
recv()[source]

Receive a message.

Return type:MessageABC
Returns:Received message.
send(msg)[source]

Send a message.

Parameters:msg (MessageABC) – Message to send.
Return type:None
aiowamp.build_message_from_list(msg_list)[source]

Create a message from msg_list.

Uses the registered message type.

Parameters:msg_list (List[ForwardRef]) – Message list containing the message type as the first element.
Return type:MessageABC
Returns:Built message.
Raises:aiowamp.InvalidMessage – If the message is invalid.
aiowamp.connect(url, *, realm, serializer=None, keyring=None)[source]

Connect to a router, join a realm, and create a client.

Parameters:
  • url (Union[str, ParseResult]) – URL of the router to connect to.
  • realm (str) – Realm to join.
  • serializer (Optional[SerializerABC]) – Serializer to use for the transport.
  • keyring (Optional[AuthKeyringABC]) – Authentication keyring.
Return type:

Client

Returns:

Client wrapping the established session.

Raises:
aiowamp.connect_transport(config)[source]

Connect a transport based on the config.

Parameters:

config (CommonTransportConfig) – Config to create the transport with.

Return type:

TransportABC

Returns:

A connected transport.

Raises:
  • KeyError – If no transport factory could be found for the config’s url.
  • Exception – If the connection fails.

Notes

Uses aiowamp.get_transport_factory to get the transport factory from which the transport is created.

aiowamp.get_message_cls(msg_type)[source]

Returns the message type registered for msg_type.

Parameters:msg_type (int) – Message type to look for.
Return type:Type[ForwardRef]
Returns:Message type registered for msg_type.
Raises:KeyError – If no message type is registered for msg_type.
aiowamp.get_transport_factory(scheme)[source]

Get the registered transport factory for the scheme.

Parameters:scheme (str) – URL scheme to get factory for.
Return type:Callable[[CommonTransportConfig], Awaitable[TransportABC]]
Returns:A transport factory callable.
Raises:KeyError – If no transport is registered for the given scheme.
aiowamp.is_message_type(msg, msg_type)[source]

Checks whether msg is of type msg_type.

This should be preferred over isinstance checks as it supports duck typing. If, however, the built-in message class is overwritten with a custom one and you depend on a specific feature of said class then isinstance should be used.

Parameters:
  • msg (MessageABC) – Message to check.
  • msg_type (Type[ForwardRef]) – Message type to check against. IMPORTANT: The function doesn’t actually cast to the type, it is assumed that if two message types share the same type code, they are interchangeable.
Return type:

bool

Returns:

Whether msg and msg_type have the same aiowamp.MessageABC.message_type.

aiowamp.join_realm(transport, realm, *, keyring=None, roles=None, details=None)[source]

Join a realm on a router.

Parameters:
  • transport (TransportABC) – Transport to run the session over.
  • realm (str) – Realm to join.
  • keyring (Optional[AuthKeyringABC]) – Authentication keyring to use for authentication.
  • roles (Optional[Dict[str, ForwardRef]]) – Roles to announce with.
  • details (Optional[Dict[str, ForwardRef]]) – Additional details to send with the hello message.
Return type:

Session

Returns:

Session running over the transport connected to the realm.

Raises:
aiowamp.message_as_type(msg, msg_type)[source]

Cast msg if it is of type msg_type.

Uses aiowamp.is_message_type to check if msg is of type msg_type.

Parameters:
  • msg (MessageABC) – Message to cast.
  • msg_type (Type[~MsgT]) – Message type to cast to.
Return type:

Optional[~MsgT]

Returns:

None, if msg is not of type msg_type, otherwise it returns msg.

Examples

This function can be used as a type guard:

>>> import aiowamp
>>> msg: aiowamp.MessageABC = aiowamp.msg.Hello(aiowamp.URI(""), {})
>>> # type of hello_msg is inferred as Optional[aiowamp.msg.Hello]
>>> hello_msg = message_as_type(msg, aiowamp.msg.Hello)
>>> hello_msg is msg
True
aiowamp.register_message_cls(*messages, overwrite=False)[source]

Register the messages.

Parameters:
  • *messages – Message types to register.
  • overwrite (bool) – If existing types should be overwritten. Defaults to False which makes overwriting an existing message type an error.
  • messages (Type[ForwardRef]) –
Raises:

ValueError – If the message type for a message is already registered by another type and overwrite is False.

Return type:

None

aiowamp.register_transport_factory(*schemes, overwrite=False)[source]

Decorator for registering transport factories.

Registered transport factories can be retrieved by aiowamp.get_transport_factory.

Parameters:
  • *schemes – Schemes to register to the given transport factory.
  • overwrite (bool) – Whether to overwrite existing registrations for a scheme. Defaults to False.
  • schemes (str) –
Raises:

ValueError – If a scheme is already registered to another factory and overwrite is False.

aiowamp.set_invocation_error(exc, err)[source]

Attach an invocation error to an exception.

This makes it possible to raise a seemingly normal python Exception while preserving the additional information for WAMP.

The attached error can then be retrieved by exception_to_invocation_error.

If the exception is an invocation error, it is overwritten with the new error.

Parameters:
  • exc (Exception) – Exception to attach the invocation error to.
  • err (InvocationError) – Invocation error to attach.
Return type:

None

Templates

aiowamp.templ.create_invocation_entry_point(fn)[source]

Create an invocation handler for the given callable.

Parameters:fn (Callable) – Function to generate invocation handler for.
Return type:Callable[[InvocationABC], Union[Awaitable[Union[ForwardRef, Tuple[ForwardRef, …], None, ForwardRef]], AsyncGenerator[Union[ForwardRef, Tuple[ForwardRef, …], None, ForwardRef], None]]]
Returns:A wrapper which acts like an entry point for the given function. It gets all arguments requested by the function’s signature from the invocation and calls it.
aiowamp.templ.create_subscription_entry_point(fn)[source]

Create subscription handler for the given callable.

Parameters:fn (Callable) – Function to generate subscription handler for.
Return type:Callable[[SubscriptionEventABC], Union[Any, Awaitable[Any]]]
Returns:A wrapper which acts like an entry point for the given function. It gets all arguments requested by the function’s signature from the subscription event and calls it.

URI Map

class aiowamp.uri_map.URIMap[source]
__init__()[source]

Initialize self. See help(type(self)) for accurate signature.

Return type:None
values()[source]
Return type:URIMapValuesView[+KV_co]
items()[source]
Return type:URIMapItemsView[+KV_co]
class aiowamp.uri_map.URIMapValuesView(mapping)[source]
Parameters:mapping (URIMap[+KV_co]) –
__init__(mapping)[source]

Initialize self. See help(type(self)) for accurate signature.

Parameters:mapping (URIMap[+KV_co]) –
Return type:None
class aiowamp.uri_map.URIMapItemsView(mapping)[source]
Parameters:mapping (URIMap[+KV_co]) –
__init__(mapping)[source]

Initialize self. See help(type(self)) for accurate signature.

Parameters:mapping (URIMap[+KV_co]) –
Return type:None