-
Notifications
You must be signed in to change notification settings - Fork 5
/
consumer.py
66 lines (50 loc) · 1.75 KB
/
consumer.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
from django.core.serializers.json import DjangoJSONEncoder
from .consumer_test import JsonRpcConsumerTest
# import the logging library
import logging
# Get an instance of a logger
logger = logging.getLogger(__name__)
class MyJsonRpcWebsocketConsumerTest(JsonRpcConsumerTest):
def connection_groups(self, **kwargs):
"""
Called to return the list of groups to automatically add/remove
this connection to/from.
"""
return ["test"]
def connect(self):
"""
Perform things on connection start
"""
logger.info("connect")
self.accept()
# reject
# self.close()
def disconnect(self, close_code):
"""
Perform things on connection close
"""
logger.info("disconnect")
# Do stuff if needed
def process(cls, data, original_msg):
"""
Made to test thread-safe
:param data:
:param original_msg:
:return:
"""
return cls.__process(data, original_msg)
@MyJsonRpcWebsocketConsumerTest.rpc_method()
def ping(fake_an_error, **kwargs):
if fake_an_error:
# Will return an error to the client
# --> {"id":1, "jsonrpc":"2.0","method":"mymodule.rpc.ping","params":{}}
# <-- {"id": 1, "jsonrpc": "2.0", "error": {"message": "fake_error", "code": -32000, "data": ["fake_error"]}}
raise Exception(False)
else:
# Will return a result to the client
# --> {"id":1, "jsonrpc":"2.0","method":"mymodule.rpc.ping","params":{}}
# <-- {"id": 1, "jsonrpc": "2.0", "result": "pong"}
return "pong"
class DjangoJsonRpcWebsocketConsumerTest(JsonRpcConsumerTest):
def encode_json(self, data):
return DjangoJSONEncoder().encode(data)