python - 使用 channel 2 向一位用户发送通知

标签 python django python-3.x websocket 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}")

最佳答案

大多数刚接触 Django-channels 2.x 的用户都面临这个问题。让我解释。
self.channel_layer.group_add("gossip", self.channel_name)接受两个参数:房间名称 channel 名称

当您通过 socket 从浏览器连接时对于这个消费者,您正在创建一个名为 channel 的新套接字连接。 .因此,当您在浏览器中打开多个页面时,会创建多个 channel 。每个 channel 都有一个唯一的 ID/名称:channel_nameroom是一组 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/

相关文章:

python - pandas.DataFrame.copy(deep=True) 实际上并没有创建深拷贝

python - 使用 django 模板时出错

python - 从 python 类引用外部范围

python - 如何找到不同值的坐标?

jquery - 我缺少什么? Django - Ajax

python - 数据框列上的 pd.Timedelta 转换

python - Django 用户传递

Django:国家下拉列表?

python-3.x - 如何从dramatiq python获取处理后的结果?

python - python中对象的完整类型