Sending Django Channels message from inside async_task

58 views Asked by At

I am using Django-Q for some moderately long tasks and would like to send a message from within the task to an websocket connection that I have established with Django channels. I am able to send the message if the task is run synchronously, ie, by calling the function, or passing sync=True to async_task. I am relatively new to this, and was not able to find out why the message is never sent, when the task is being run asynchronously. Is this not possible to achieve, or what is it that I am missing?

I am aware that I could use Celery for this, though I would prefer not to unless this cannot be done with Django-Q.

Here is the setup:

#views.py

def testview(request, uuid):

    task_id = async_task(dummy_task, uuid)
    event_triger(uuid, task_id) # This message shows up. 

def event_triger(uuid, message):
    channel_layer = get_channel_layer()
    async_to_sync(channel_layer.group_send)(
        uuid,
        {
            'type': 'send_message_to_frontend',
            'message': message
        }
    ) 

def dummy_task(uuid):
    for i in range(3):
        event_triger(uuid, "")
        time.sleep(3)

The consumers.py file has the following:

class NotificationConsumer(WebsocketConsumer):
    
    def connect(self):
        self.uuid = self.scope["url_route"]["kwargs"]["uuid"]
        async_to_sync(self.channel_layer.group_add)(
            self.uuid,
            self.channel_name
        )
        self.accept()

        self.send(text_data = json.dumps({
            "type": "est",
            "msg": self.uuid,
            "channel": self.channel_name
            
        }))
    
    def disconnect(self, code):
        async_to_sync(self.channel_layer.group_discard)(
            self.uuid,
            self.channel_name
        )
        print("DISCONNECED CODE: ",code)

    
    def send_message_to_frontend(self,event):
        print("EVENT TRIGERED")
        # Receive message from room group
        message = event['message']
        # Send message to WebSocket
        self.send(text_data=json.dumps({
            'message': message
        }))
0

There are 0 answers