Django频道未收到消息

时间:2020-05-07 04:28:53

标签: django django-channels

我在当前项目中使用django频道。我正在从我的django应用程序之一向通道层发送通知,以便websocket可以广播消息。但是问题是 消费者没有收到我的消息。

django应用程序中的实用程序,用于将通知发送到频道:

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


def async_send(group_name, text):
    channel_layer = get_channel_layer()
    AsyncToSync(channel_layer.group_send)(
        group_name,
        {
            'type': 'notify',
            'text': json.dumps(text)
        }
    )

我的使用者文件是:

from channels.generic.websocket import AsyncWebsocketConsumer


class InformationConsumer(AsyncWebsocketConsumer):
    async def connect(self):
        self.channel_layer.group_add(str(self.scope['user']), self.channel_name)
        await self.accept()

    async def notify(self, event):
        await self.send(
            {
                "message": event['text'],
            },
        )
        print(event['text'])

我应该得到event ['text']的输出,但是什么也没有得到:(

1 个答案:

答案 0 :(得分:3)

更改

self.channel_layer.group_add(str(self.scope['user']), self.channel_name)

await self.channel_layer.group_add(str(self.scope['user']), self.channel_name)