使用通道2向一个用户发送通知

2024-06-13 12:02:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我想使用通道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}")


Tags: to用户nameself身份验证eventlayerasync
1条回答
网友
1楼 · 发布于 2024-06-13 12:02:37

大多数刚接触Django channels 2.x的用户都面临这个问题。让我解释一下。在

self.channel_layer.group_add("gossip", self.channel_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发送/广播消息时,它将只由该用户接收。在

相关问题 更多 >