API Reference#

class wsrpc_aiohttp.websocket.abc.AbstractWSRPC(loop: AbstractEventLoop | None = None, timeout: int | float | None = None)[source]#
abstract classmethod add_route(route: str, handler: Callable[[WSRPC, P], Any] | Type[AbstractRoute]) None[source]#

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.

In case the method of class will be called first, wsrpc_aiohttp.WebSocketRoute.init() will be called without params before callable method.

class wsrpc_aiohttp.websocket.abc.AbstractWebSocket(request: Request)[source]#
abstract async authorize() bool[source]#

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

abstract classmethod broadcast(func, callback=None, return_exceptions=True, **kwargs: Mapping[str, Any]) Task[source]#

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 = None)[source]#

Cancel all pending tasks and stop this socket connection

abstract classmethod configure(keepalive_timeout: int | float, client_timeout: int | float, max_concurrent_requests: int) None[source]#

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.abc.WSRPCBase(loop: AbstractEventLoop | None = None, timeout: int | float | None = None)[source]#
abstract async call(func: str, timeout: int | float | None = None, **kwargs: Mapping[str, Any])[source]#

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 self.socket.proxy.ping()
    return foo + bar

class RemoteClass(WebSocketRoute):

    # this method executes when remote side call route name
    asyc 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[str, AbstractWSRPC]#

Property which contains the socket clients

abstract async close(message: WSMessage | None = None)[source]#

Cancel all pending tasks

abstract property proxy: 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)[source]#

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

class wsrpc_aiohttp.websocket.client.WSRPCClient(endpoint: ~yarl.URL | str, loop=None, timeout=None, session: ~aiohttp.client.ClientSession | None = None, loads=<function loads>, dumps=<function dumps>, **kwargs)[source]#

WSRPC Client class

async close()[source]#

Close the client connect connection

async connect()[source]#

Perform connection to the server

exception wsrpc_aiohttp.websocket.common.ClientException(payload)[source]#
class wsrpc_aiohttp.websocket.common.WSRPCBase(loop: ~asyncio.events.AbstractEventLoop | None = None, timeout: int | float | None = None, loads: ~typing.Callable[[...], ~typing.Any] = <function loads>, dumps: ~typing.Callable[[...], str] = <function dumps>)[source]#

Common WSRPC abstraction

classmethod add_route(route: str, handler: Callable[[...], Any] | Type[AbstractRoute]) None[source]#

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.

In case the method of class will be called first, wsrpc_aiohttp.WebSocketRoute.init() will be called without params before callable method.

async call(func: str, timeout=None, **kwargs)[source]#

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 self.socket.proxy.ping()
    return foo + bar

class RemoteClass(WebSocketRoute):

    # this method executes when remote side call route name
    asyc 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[str, AbstractWSRPC]#

Property which contains the socket clients

async close(message=None)[source]#

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)[source]#

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

exception wsrpc_aiohttp.websocket.common.WSRPCError[source]#
class wsrpc_aiohttp.websocket.decorators.NoProxyFunction[source]#
class wsrpc_aiohttp.websocket.decorators.ProxyBase[source]#
class wsrpc_aiohttp.websocket.decorators.ProxyFunction[source]#
exception wsrpc_aiohttp.websocket.handler.ClientException(payload)[source]#
class wsrpc_aiohttp.websocket.handler.WebSocketAsync(request)[source]#

Handler class which execute any route as a coroutine

class wsrpc_aiohttp.websocket.handler.WebSocketBase(request)[source]#

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 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 most compact representation.

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[source]#

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)[source]#

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)[source]#

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>)[source]#

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()[source]#

Freeze all signals

class wsrpc_aiohttp.websocket.handler.WebSocketThreaded(request)[source]#

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

wsrpc_aiohttp.websocket.tools.serializer(value)[source]#
wsrpc_aiohttp.websocket.tools.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}}