Quiz
1import json
2from channels.generic.websocket import AsyncWebsocketConsumer
3
4
5class GamesConsumer(AsyncWebsocketConsumer):
6
7async def connect(self):
8options = ['user', 'queue', 'game']
9for option in options:
10try:
11name = f"{option}_{self.scope['url_route']['kwargs'][f'{option}_id']}"
12except:
13pass
14
15self.group_name = name
16
17await self.channel_layer.group_add(self.group_name, self.channel_name)
18
19await self.accept()
20
21async def disconnect(self, code):
22
23await self.channel_layer.group_discard(self.group_name, self.channel_name)
24
25async def receive(self, text_data):
26text_data_json = json.loads(text_data)
27message = text_data_json['message']
28
29event = {
30'type': 'send_message',
31'message': message
32}
33
34await self.channel_layer.group_send(self.group_name, event)
35
36async def send_message(self, event):
37message = event['message']
38
39await self.send(text_data=json.dumps({'message': message}))
40