Django频道没有收到消息

问题描述 投票:0回答:1

我在目前的项目中使用了django channel,从我的一个django app中向channel层发送通知,这样websocket就可以广播消息。从我的一个django应用中,我正在发送通知到channel层,以便websocket可以广播消息。但问题是消费者没有收到我的消息。

在django应用中,我使用了什么方法来发送通知到channel。

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']的输出,但是什么都没有得到:(

django django-channels
1个回答
2
投票

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)

© www.soinside.com 2019 - 2024. All rights reserved.