使用频道 2 向一位用户发送通知

Muk*_*osh 3 python django websocket python-3.x django-channels

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

Run Code Online (Sandbox Code Playgroud)

whi*_*hat 16

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

self.channel_layer.group_add("gossip", self.channel_name)接受两个参数:room_namechannel_name

当您通过浏览器连接socket到此使用者时,您正在创建一个名为 as 的新套接字连接channel。因此,当您在浏览器中打开多个页面时,会创建多个频道。每个频道都有一个唯一的 Id/name :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
    )
Run Code Online (Sandbox Code Playgroud)

每当您向 发送/广播消息时user_room_name,它只会被该用户接收。

  • 您好。如何从班级外部向“user_room_name”发送广播消息,例如“view”?谢谢 (2认同)