3π
To send messages asynchronously you should use async,
and write an async function to send data on the requirement, call the send function in view.py or a celery worker, if you want to send periodically celery beat is the way to go else use celery workers for on-demand data.
Itβs my first time answering in the stack if there is any mistake in my understanding of question or in my the answer please pardon me. and I am not sure about what is your first question.
(I have just started learning Vue js but I have worked for years on Django so I thought I could answer this as thank you to all people who helped me with responses in Stackoverflow.com)
below is a simple example of socket connection I have implemented:
class NotificationConsumer(AsyncWebsocketConsumer):
async def connect(self):
# this only exicutes only once when a user gets connected to the socket
self.room_name = self.scope['url_route']['kwargs']['room_name']
self.room_group_name = 'notification_%s' % self.room_name
# Join room group
await self.channel_layer.group_add(
self.room_group_name,
self.channel_name
)
await self.accept()
async def disconnect(self, close_code):
# Leave room group
await self.channel_layer.group_discard(
self.room_group_name,
self.channel_name
)
Receive message from WebSocket
async def receive(self, text_data):
text_data_json = json.loads(text_data)
message = text_data_json['message']
print(message)
print("message")
# Send message to room group
await self.channel_layer.group_send(
self.room_group_name,
{
'type': 'snmpop_message',
'message': message
}
)
async def send_notification(self, event):
message = json.loads(event['message'])
print(message)
# Send message to WebSocket
await self.send(text_data=json.dumps(message))
#This is how I will send the data on requirement: from any other place:
channel_layer = get_channel_layer()
async_to_sync(channel_layer.group_send)(
"notification_broadcast",
{
'type': 'send_Notification',
'message': json.dumps(outputdict)
}
)
if any of you have queries you can reach out to me: amithkhul@gmail.com
Thank you
Amith K