Guest User

Untitled

a guest
May 26th, 2025
27
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.38 KB | Source Code | 0 0
  1. import json
  2. from channels.consumer import AsyncConsumer
  3.  
  4. from channels.generic.websocket import AsyncJsonWebsocketConsumer
  5. import base64
  6.  
  7.  
  8. # Channel consumer for both chat room group
  9.  
  10. class ChatConsumer(AsyncJsonWebsocketConsumer):
  11.     async def connect(self):
  12.         self.room_name = self.scope['url_route']['kwargs']['room_name']
  13.         self.room_group_name = 'chat_%s' % self.room_name
  14.        
  15.         # Join room group
  16.         await self.channel_layer.group_add(self.room_group_name, self.channel_name)
  17.        
  18.         await self.accept()
  19.        
  20.        
  21.     async def disconnect(self, close_code):
  22.  
  23.         # Leave room group
  24.         await self.channel_layer.group_discard(self.room_group_name, self.channel_name)
  25.        
  26.     # Receive message from WebSocket
  27.    
  28.     async def receive(self, text_data):
  29.         text_data_json = json.loads(text_data)
  30.         message = text_data_json['message']
  31.         print(f"Received message: {message}")
  32.         # Send message to room group
  33.         await self.channel_layer.group_send(
  34.             self.room_group_name, {'type': 'chat.message', 'message': message}
  35.         )
  36.        
  37.     # Receive message from room group
  38.    
  39.     async def chat_message(self, event):
  40.         message = event['message']
  41.         print(f"Broadcasting message: {message}")  # Debugging output
  42.         # send message to websocket
  43.         await self.send(text_data=json.dumps({'message': message}))
  44.        
  45.        
  46. # Channel Consumer that consumed events for uploading/receiving image files in the message room
  47.  
  48. class UploadImageConsumer(AsyncJsonWebsocketConsumer):
  49.     async def connect(self):
  50.         await self.accept()
  51.        
  52.  
  53.     async def disconnect(self, close_code):
  54.  
  55.         async def receive(self, bytes_data=None, text_data=None):
  56.             if bytes_data:
  57.             # Handles image file chunks (binary data)
  58.            
  59.                 with open('image.jpg', 'rb') as f:
  60.                     fcontent = f.read()
  61.                 await self.send(base64.b64encode(fcontent).decode('utf-8'))
  62.             elif text_data:
  63.                 # Handles metadata (text data)
  64.            
  65.                 await self.send(text_data=json.dumps({'message': text_data}))
  66.            
  67.            
  68.     async def send_image(self, event):
  69.         image_data = event['image_text']
  70.         await self.send(bytes_data=image_data)
  71.        
  72.        
Add Comment
Please, Sign In to add comment