API reference

The public classes below are importable from wsrpc_aiohttp. See routes and connections for complete examples and signals for lifecycle callback arguments.

Connections, routes and serialization

WSRPCClient is the Python peer. WebSocketAsync and WebSocketThreaded are aiohttp handlers; both inherit connection configuration from WebSocketBase. WSRPCBase contains the shared RPC interface.

Route classes are generic over the socket type, for example Route[WebSocketAsync]. The decorators module controls which methods are exposed. STATIC_DIR is the installed directory containing the JavaScript client.

class wsrpc_aiohttp.AllowedRoute(socket: SocketT)
exception wsrpc_aiohttp.ClientException(payload)
class wsrpc_aiohttp.PrefixRoute(socket: SocketT)
class wsrpc_aiohttp.Route(socket: SocketT)
class wsrpc_aiohttp.WSRPCBase(loop: ~asyncio.events.AbstractEventLoop | None = None, timeout: int | float | None = None, loads: ~collections.abc.Callable[[...], ~typing.Any] = <function loads>, dumps: ~collections.abc.Callable[[...], str] = <function dumps>)

Common WSRPC abstraction

classmethod add_route(route: str, handler: Callable[[...], Any] | type[AbstractRoute]) → None

Expose local function through RPC

Parameters:
  • route – Name which function will be aliased for this function. Remote side should call function by this name.

  • handler – Function or Route class (classes based on wsrpc_aiohttp.WebSocketRoute). For route classes the public methods will be registered automatically.

Note

Route classes might be initialized only once for the each socket instance.

A route instance is created lazily for each connection. Calling the bare route name resolves its exposed init method; init is not called automatically before other methods.

async call(func: str, timeout=None, **kwargs)

Method for call remote function

Remote methods allows only kwargs as arguments.

You might use functions as route or classes

async def remote_function(socket: WSRPCBase, *, foo, bar):
    # call function from the client-side
    await socket.proxy.ping()
    return foo + bar

class RemoteClass(WebSocketRoute):

    # this method executes when remote side call route name
    async def init(self):
        # call function from the client-side
        await self.socket.proxy.ping()

    async def make_something(self, foo, bar):
        return foo + bar
property clients: dict[UUID, AbstractWSRPC]

Property which contains the socket clients

async close(message=None)

Cancel all pending tasks

property proxy

Special property which allow run the remote functions by dot notation

# calls remote function with name ping
await client.proxy.ping()

# full equivalent of
await client.call('ping')
classmethod remove_route(route: str, fail=True)

Removes route by name. If fail=True an exception will be raised in case the route was not found.

property routes: dict[str, Callable[[...], Any] | type[AbstractRoute]]

Property which contains the socket routes

class wsrpc_aiohttp.WSRPCClient(endpoint: URL | str, loop=None, timeout=None, session: ClientSession | None = None, loads=<function loads>, dumps=<function dumps>, **kwargs)

WSRPC Client class

async close(message: WSMessage | None = None)

Close the client connect connection

async connect()

Perform connection to the server

exception wsrpc_aiohttp.WSRPCError
class wsrpc_aiohttp.WebSocketAsync(request)

Handler class which execute any route as a coroutine

class wsrpc_aiohttp.WebSocketBase(request)

Base class for aiohttp websocket handler

static JSON_DUMPS(obj, *, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, default=None, sort_keys=False, **kw)

Serialize obj to a JSON formatted str.

If skipkeys is true then dict keys that are not basic types (str, int, float, bool, None) will be skipped instead of raising a TypeError.

If ensure_ascii is false, then the return value can contain non-ASCII and non-printable characters if they appear in strings contained in obj. Otherwise, all such characters are escaped in JSON strings.

If check_circular is false, then the circular reference check for container types will be skipped and a circular reference will result in an RecursionError (or worse).

If allow_nan is false, then it will be a ValueError to serialize out of range float values (nan, inf, -inf) in strict compliance of the JSON specification, instead of using the JavaScript equivalents (NaN, Infinity, -Infinity).

If indent is a non-negative integer, then JSON array elements and object members will be pretty-printed with that indent level. An indent level of 0 will only insert newlines. None is the default and gives a representation with no newlines inserted.

If specified, separators should be an (item_separator, key_separator) tuple. The default is (', ', ': ') if indent is None and (',', ': ') otherwise. To get the most compact JSON representation, you should specify (',', ':') to eliminate whitespace.

default(obj) is a function that should return a serializable version of obj or raise TypeError. The default simply raises TypeError.

If sort_keys is true (default: False), then the output of dictionaries will be sorted by key.

To use a custom JSONEncoder subclass (e.g. one that overrides the .default() method to serialize additional types), specify it with the cls kwarg; otherwise JSONEncoder is used.

static JSON_LOADS(s, *, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, **kw)

Deserialize s (a str, bytes or bytearray instance containing a JSON document) to a Python object.

object_hook is an optional function that will be called with the result of any object literal decode (a dict). The return value of object_hook will be used instead of the dict. This feature can be used to implement custom decoders (e.g. JSON-RPC class hinting).

object_pairs_hook is an optional function that will be called with the result of any object literal decoded with an ordered list of pairs. The return value of object_pairs_hook will be used instead of the dict. This feature can be used to implement custom decoders. If object_hook is also defined, the object_pairs_hook takes priority.

parse_float, if specified, will be called with the string of every JSON float to be decoded. By default this is equivalent to float(num_str). This can be used to use another datatype or parser for JSON floats (e.g. decimal.Decimal).

parse_int, if specified, will be called with the string of every JSON int to be decoded. By default this is equivalent to int(num_str). This can be used to use another datatype or parser for JSON integers (e.g. float).

parse_constant, if specified, will be called with one of the following strings: -Infinity, Infinity, NaN. This can be used to raise an exception if invalid JSON numbers are encountered.

To use a custom JSONDecoder subclass, specify it with the cls kwarg; otherwise JSONDecoder is used.

async authorize() → bool

Special method for authorize client. If this method return True then access allowed, otherwise 403 Forbidden will be sent.

This method will be called before socket connection establishment.

By default everyone has access. You have to inherit this class and change this behaviour.

Note

You can validate some headers (self.request.headers) or check cookies (self.reauest.cookies).

classmethod broadcast(func, callback=None, return_exceptions=True, **kwargs)

Call remote function on all connected clients

Parameters:
  • func – Remote route name

  • callback – Function which receive responses

  • return_exceptions – Return exceptions of client calls instead of raise a first one

async close(message=None)

Cancel all pending tasks and stop this socket connection

classmethod configure(keepalive_timeout=30, client_timeout=10, max_concurrent_requests=25, loads=<function loads>, dumps=<function dumps>)

Configures the handler class

Parameters:
  • dumps – json serializer

  • loads – json deserializer

  • keepalive_timeout – sets timeout of client pong response

  • client_timeout – internal lock timeout

  • max_concurrent_requests – how many concurrent requests might be performed by each client

classmethod freeze()

Freeze all signals

class wsrpc_aiohttp.WebSocketRoute(socket: SocketT)
class wsrpc_aiohttp.WebSocketThreaded(request)

Handler class which execute any route in the default thread-pool of current event loop

wsrpc_aiohttp.serializer(value)
wsrpc_aiohttp.serializer(value: bytes)

singledispatch wrapped function. You might register custom types if you want pass it to the remote side.

from wsrpc_aiohttp import serializer

class MyObject:
    def __init__(self):
        self.foo = 'bar'

@serializer.register(MyObject)
def _(value: MyObject) -> dict:
    return {'myObject': {'foo': value.foo}}

Method decorators

Signals

class wsrpc_aiohttp.signal.Signal

Interfaces and helpers

The following modules define abstract connection interfaces and utility types used by the implementation. Applications normally use the public connection and route classes above.

class wsrpc_aiohttp.websocket.abc.AbstractRoute(socket: SocketT)
class wsrpc_aiohttp.websocket.abc.AbstractWSRPC(loop: AbstractEventLoop | None = None, timeout: int | float | None = None)
abstractmethod classmethod add_route(route: str, handler: Callable[[Concatenate[WSRPC, P]], Any] | type[AbstractRoute]) → None

Expose local function through RPC

Parameters:
  • route – Name which function will be aliased for this function. Remote side should call function by this name.

  • handler – Function or Route class (classes based on wsrpc_aiohttp.WebSocketRoute). For route classes the public methods will be registered automatically.

Note

Route classes might be initialized only once for each socket instance.

A route instance is created lazily for each connection. Calling the bare route name resolves its exposed init method; init is not called automatically before other methods.

class wsrpc_aiohttp.websocket.abc.AbstractWebSocket(request: Request)
abstractmethod async authorize() → bool

Special method for authorize client. If this method return True then access allowed, otherwise 403 Forbidden will be sent.

This method will be called before socket connection establishment.

By default everyone has access. You have to inherit this class and change this behaviour.

Note

You can validate some headers (self.request.headers) or check cookies (self.reauest.cookies).

abstractmethod classmethod broadcast(func, callback=None, return_exceptions=True, **kwargs: Any) → Task

Call remote function on all connected clients

Parameters:
  • func – Remote route name

  • callback – Function which receive responses

  • return_exceptions – Return exceptions of client calls instead of raise a first one

async close(message: Any = None)

Cancel all pending tasks and stop this socket connection

abstractmethod classmethod configure(keepalive_timeout: int | float, client_timeout: int | float, max_concurrent_requests: int) → None

Configures the handler class

Parameters:
  • keepalive_timeout – sets timeout of client pong response

  • client_timeout – internal lock timeout

  • max_concurrent_requests – how many concurrent requests might be performed by each client

class wsrpc_aiohttp.websocket.tools.Lazy(func: Callable[[], T])