|
| 1 | +Signals |
| 2 | +======= |
| 3 | + |
| 4 | +Signals allow to set callbacks on some events: |
| 5 | + |
| 6 | +- ``ON_CONN_OPEN(socket, request)`` - when new websocket connection |
| 7 | + establishing, before authentication |
| 8 | +- ``ON_CONN_CLOSE(socket, request)`` - right before closing a |
| 9 | + connection |
| 10 | +- ``ON_AUTH_SUCCESS(socket, request)`` - after successfully |
| 11 | + authenticate new connection |
| 12 | +- ``ON_AUTH_FAIL(socket, request)`` - on authentication failure |
| 13 | +- ``ON_CALL_START(method, serial, args, kwargs)`` - on procedure call, |
| 14 | + before executing corresponding handler |
| 15 | +- ``ON_CALL_SUCCESS(method, serial, args, kwargs)`` - on success |
| 16 | + procedure call, before sending a reply |
| 17 | +- ``ON_CALL_FAIL(method, serial, args, kwargs)`` - on exception raised |
| 18 | + from procedure handler |
| 19 | + |
| 20 | +Example: |
| 21 | + |
| 22 | +.. code:: python |
| 23 | +
|
| 24 | + import asyncio |
| 25 | + import logging |
| 26 | + import random |
| 27 | + from contextvars import ContextVar |
| 28 | + from time import time |
| 29 | +
|
| 30 | + import aiohttp.web |
| 31 | + from wsrpc_aiohttp import ( |
| 32 | + Route, STATIC_DIR, WebSocketAsync, WebSocketRoute, decorators |
| 33 | + ) |
| 34 | +
|
| 35 | +
|
| 36 | + call_started_at = ContextVar("call_started_at") |
| 37 | +
|
| 38 | + log = logging.getLogger(__name__) |
| 39 | +
|
| 40 | +
|
| 41 | + class TestRoute(Route): |
| 42 | +
|
| 43 | + @decorators.proxy |
| 44 | + async def slow_proc(self): |
| 45 | + await asyncio.sleep(random.randint(1, 10) / 10) |
| 46 | + return True |
| 47 | +
|
| 48 | + # Signal handlers |
| 49 | + async def on_call_start(method, **kwargs): |
| 50 | + ts = time() |
| 51 | + log.debug("Method %s called at %f", method, ts) |
| 52 | + call_started_at.set(ts) |
| 53 | +
|
| 54 | +
|
| 55 | + async def on_call_end(method, **kwargs): |
| 56 | + ts = time() - call_started_at.get() |
| 57 | + log.info("Method %s processed for %f", method, ts) |
| 58 | +
|
| 59 | + # Connecting handlers to signals |
| 60 | + WebSocketAsync.ON_CALL_START.connect(on_call_start) |
| 61 | + WebSocketAsync.ON_CALL_SUCCESS.connect(on_call_end) |
| 62 | +
|
| 63 | +
|
| 64 | + app = aiohttp.web.Application() |
| 65 | + app.router.add_route("*", "/ws/", WebSocketAsync) # Websocket route |
| 66 | + app.router.add_static('/', ".") # Your static files |
| 67 | +
|
| 68 | + WebSocketAsync.add_route('test', TestRoute) |
| 69 | +
|
| 70 | +
|
| 71 | + if __name__ == '__main__': |
| 72 | + logging.basicConfig(level=logging.INFO) |
| 73 | + aiohttp.web.run_app(app, port=8000, access_log=None) |
0 commit comments