我想使用 Channels 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}")
最佳答案
大多数刚接触 Django-channels 2.x 的用户都面临这个问题。让我解释。self.channel_layer.group_add("gossip", self.channel_name)
接受两个参数:房间名称和 channel 名称
当您通过 socket
从浏览器连接时对于这个消费者,您正在创建一个名为 channel
的新套接字连接。 .因此,当您在浏览器中打开多个页面时,会创建多个 channel 。每个 channel 都有一个唯一的 ID/名称:channel_name
room
是一组 channel 。如果有人发消息到room
,该 channel 中的所有 channel 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
发送/广播消息时, 只会由该用户接收。
关于python - 使用 channel 2 向一位用户发送通知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55310717/