发送通知给一个用户使用频道2(sending notification to one user us

2019-10-29 04:08发布

我想用频道2发送通知给特定的身份验证的用户。

在下面的代码我发送通知的广播,而不是我想通知发送到特定的用户。

from channels.generic.websocket import AsyncJsonWebsocketConsumer


class NotifyConsumer(AsyncJsonWebsocketConsumer):

    async def connect(self):
        await self.accept()
        await self.channel_layer.group_add("gossip", self.channel_name)
        print(f"Added {self.channel_name} channel to gossip")

    async def disconnect(self, close_code):
        await self.channel_layer.group_discard("gossip", self.channel_name)
        print(f"Removed {self.channel_name} channel to gossip")

    async def user_gossip(self, event):
        await self.send_json(event)
        print(f"Got message {event} at {self.channel_name}")

Answer 1:

大多数用户新的Django通道2.x的面对这个问题。 让我解释。

self.channel_layer.group_add("gossip", self.channel_name)有两个参数:ROOM_NAMECHANNEL_NAME

当您通过您的浏览器连接socket到这种消费,要创建称为新的套接字连接channel 。 所以,当你在浏览器中打开多个页面,创建了多个通道。 每个通道都有一个唯一的ID /名称: channel_name

room是一组信道。 如果有人将消息发送到了room ,在所有通道room将收到该消息。

所以,如果你需要发送一个通知/信息给一个用户,那么你必须创建一个room只对特定的用户。

假设当前user是在消费者的传递scope

self.user = self.scope["user"]
self.user_room_name = "notif_room_for_user_"+str(self.user.id) ##Notification room name
await self.channel_layer.group_add(
       self.user_room_name,
       self.channel_name
    )

只要发送/广播消息user_room_name ,它只能由该用户接收。



文章来源: sending notification to one user using Channels 2