7
7
from .config import APP_CLIENT_SOCKET_DECORATED_HANDLERS_KEY , get_socket_server
8
8
9
9
10
+ socketio_handlers_registry = []
11
+
12
+
10
13
def socket_io_handler (app : web .Application ):
11
14
"""this decorator allows passing additional paramters to python-socketio compatible handlers.
12
15
I.e. python-socketio handler expect functions of type `async def function(sid, *args, **kwargs)`
@@ -18,6 +21,7 @@ def decorator(func):
18
21
async def wrapped (* args , ** kwargs ):
19
22
return await func (* args , ** kwargs , app = app )
20
23
24
+
21
25
return wrapped
22
26
23
27
return decorator
@@ -33,18 +37,34 @@ def has_socket_io_handler_signature(fun) -> bool:
33
37
34
38
def register_handlers (app : web .Application , module : ModuleType ):
35
39
sio = get_socket_server (app )
36
- predicate = (
37
- lambda obj : inspect .isfunction (obj )
38
- and has_socket_io_handler_signature (obj )
39
- and inspect .iscoroutinefunction (obj )
40
- and inspect .getmodule (obj ) == module
41
- )
42
- member_fcts = inspect .getmembers (module , predicate )
40
+ member_fcts = [
41
+ fct for fct in socketio_handlers_registry if inspect .getmodule (fct ) == module
42
+ ]
43
43
# convert handler
44
44
partial_fcts = [
45
- socket_io_handler (app )(func_handler ) for _ , func_handler in member_fcts
45
+ socket_io_handler (app )(func_handler ) for func_handler in member_fcts
46
46
]
47
47
app [APP_CLIENT_SOCKET_DECORATED_HANDLERS_KEY ] = partial_fcts
48
48
# register the fcts
49
49
for func in partial_fcts :
50
50
sio .on (func .__name__ , handler = func )
51
+
52
+
53
+ def register_socketio_handler (func : callable ) -> callable :
54
+ """this decorator appends handlers to a registry if they fit certain rules
55
+
56
+ :param func: the function to call
57
+ :type func: callable
58
+ :return: the function to call
59
+ :rtype: callable
60
+ """
61
+ is_handler = (
62
+ inspect .isfunction (func )
63
+ and has_socket_io_handler_signature (func )
64
+ and inspect .iscoroutinefunction (func )
65
+ )
66
+ if is_handler :
67
+ socketio_handlers_registry .append (func )
68
+ else :
69
+ raise SyntaxError ("the function shall be of type fct(*args, app: web.Application" )
70
+ return func
0 commit comments