[Django]-Django Channels 2.0 channel_layers not communicating

8👍

After a reply from Andres Godwin:

I turns out it was a bug in asgiref < 2.1.3, by upgrading the return values from SyncToAsync/AsyncToSync have been fixed!

So my working implementation, for anyone who’s interested:

consumers.py

from channels.consumer import AsyncConsumer

class My_Consumer(AsyncConsumer):

async def websocket_connect(self, event):
    print("Connected")
    print(event)
    print(self.channel_name)
    await self.send({
        "type": "websocket.accept",
    })

async def websocket_receive(self, event):
    print("Received")
    print(event)
    parse_api_request(self.channel_name, json.loads(event['text']))

async def celery_message(self, event):
    print("Service Received")
    print(event)
    await self.send({
        "type": "websocket.send",
        "text": event["text"],
    })


task.py 

from channels.layers import get_channel_layer
from asgiref.sync import AsyncToSync


def async_send(channel_name, text):
    channel_layer = get_channel_layer()
    AsyncToSync(channel_layer.send)(
            channel_name,
            {"type": "celery.message",
             "text": json.dumps(text)
             })


def getAFTree(channel_name, message):
    getAFTreeTask.delay(channel_name, message)



@task
def getAFTreeTask(channel_name, message):
    tree = Request().cache_af_tree()
    async_send(channel_name, {
                "channel": "AF_INIT",
                "payload": tree
             })
👤Chris

Leave a comment