【发布时间】:2020-05-07 04:28:53
【问题描述】:
我在当前项目中使用 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'] 的输出,但什么也没得到 :(
【问题讨论】:
-
组名是什么?
-
如何调用 utils
-
我通过用户名调用组名。比如 async_send(str(request.user.username), 'Hello ')
-
把这个 1 改成 2 和 2 nd 改成 1 self.channel_layer.group_add(str(self.scope['user']), self.channel_name) await self.accept()
-
@giveJob 它不工作:(