API Reference#
- class wsrpc_aiohttp.websocket.abc.AbstractWSRPC(loop: Optional[AbstractEventLoop] = None, timeout: Optional[Union[int, float]] = None)[source]#
- abstract classmethod add_route(route: str, handler: Union[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: Optional[Any] = None)[source]#
Cancel all pending tasks and stop this socket connection
- abstract classmethod configure(keepalive_timeout: Union[int, float], client_timeout: Union[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: Optional[AbstractEventLoop] = None, timeout: Optional[Union[int, float]] = None)[source]#
- abstract async call(func: str, timeout: Optional[Union[int, float]] = 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 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')
- class wsrpc_aiohttp.websocket.client.WSRPCClient(endpoint: ~typing.Union[~yarl.URL, str], loop=None, timeout=None, session: ~typing.Optional[~aiohttp.client.ClientSession] = None, loads=<function loads>, dumps=<function dumps>, **kwargs)[source]#
WSRPC Client class
- class wsrpc_aiohttp.websocket.common.WSRPCBase(loop: ~typing.Optional[~asyncio.events.AbstractEventLoop] = None, timeout: ~typing.Optional[~typing.Union[int, float]] = None, loads: ~typing.Callable[[...], ~typing.Any] = <function loads>, dumps: ~typing.Callable[[...], str] = <function dumps>)[source]#
Common WSRPC abstraction
- classmethod add_route(route: str, handler: Union[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
- 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, Union[Callable[[...], Any], Type[AbstractRoute]]]#
Property which contains the socket routes
- 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 formattedstr
.If
skipkeys
is true thendict
keys that are not basic types (str
,int
,float
,bool
,None
) will be skipped instead of raising aTypeError
.If
ensure_ascii
is false, then the return value can contain non-ASCII characters if they appear in strings contained inobj
. 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 anRecursionError
(or worse).If
allow_nan
is false, then it will be aValueError
to serialize out of rangefloat
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 isNone
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 thecls
kwarg; otherwiseJSONEncoder
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
(astr
,bytes
orbytearray
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 (adict
). The return value ofobject_hook
will be used instead of thedict
. 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 ofobject_pairs_hook
will be used instead of thedict
. This feature can be used to implement custom decoders. Ifobject_hook
is also defined, theobject_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 thecls
kwarg; otherwiseJSONDecoder
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
- 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
- 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}}