-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathutils.py
75 lines (62 loc) · 1.57 KB
/
utils.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
__all__ = (
'clear_task',
'is_valid_json',
'serialize',
'deserialize',
'update',
'is_valid_broker',
)
import asyncio
import inspect
import json
from typing import Any
def clear_task(task: asyncio.Task) -> None:
if task.done():
task.result()
else:
task.cancel()
def is_valid_json(data: Any) -> bool:
try:
json.loads(data)
except ValueError:
return False
return True
def serialize(obj: Any) -> Any:
assert hasattr(
obj, '__serialize__'
), 'Object must have __serialize__ method'
return obj.__serialize__()
def deserialize(obj: Any) -> Any:
assert hasattr(
obj, '__deserialize__'
), 'Object must have __deserialize__ method'
return obj.__deserialize__()
def update(obj: dict, **kwargs) -> dict:
new_obj = obj.copy()
new_obj.update(**kwargs)
return new_obj
def is_valid_broker(obj: Any) -> bool:
"""
Helper utils to check if an object can
be used as a broker in `WebSocketManager`.
Exposed to developers who need to implement a
custom broker.
"""
return (
(
hasattr(obj, 'subscribe')
and inspect.iscoroutinefunction(obj.subscribe)
)
and (
hasattr(obj, 'unsubscribe')
and inspect.iscoroutinefunction(obj.unsubscribe)
)
and (
hasattr(obj, 'publish')
and inspect.iscoroutinefunction(obj.publish)
)
and (
hasattr(obj, 'get_message')
and inspect.iscoroutinefunction(obj.get_message)
)
)