我在目前的项目中使用了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']的输出,但是什么都没有得到:(
从
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)