EdulabBackend / apps /notifications /consumers.py
rinogeek's picture
Initial commit: EduLab Backend for Hugging Face Spaces
d42510a
import json
from channels.generic.websocket import AsyncWebsocketConsumer
from channels.db import database_sync_to_async
class NotificationConsumer(AsyncWebsocketConsumer):
async def connect(self):
self.user = self.scope["user"]
if not self.user.is_authenticated:
await self.close()
return
self.group_name = f"user_{self.user.id}"
# Join user group
await self.channel_layer.group_add(
self.group_name,
self.channel_name
)
await self.accept()
async def disconnect(self, close_code):
if hasattr(self, 'group_name'):
# Leave user group
await self.channel_layer.group_discard(
self.group_name,
self.channel_name
)
# Receive message from user group
async def notification_message(self, event):
# Send message to WebSocket
await self.send(text_data=json.dumps({
'type': 'notification',
'notification': event['notification']
}))