【问题标题】:sending notification to one user using Channels 2使用通道 2 向一位用户发送通知
【发布时间】:2019-08-14 02:17:45
【问题描述】:

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

【问题讨论】:

    标签: python django python-3.x websocket django-channels


    【解决方案1】:

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

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

    当您从浏览器通过socket 连接到此消费者时,您正在创建一个名为<b>channel</b> 的新套接字连接。因此,当您在浏览器中打开多个页面时,会创建多个频道。每个频道都有一个唯一的 ID/名称:<b>channel_name</b>

    <b>room</b> 是一组频道。如果有人向<b>room</b> 发送消息,则<b>room</b> 中的所有频道都会收到该消息。

    因此,如果您需要向单个用户发送通知/消息,则必须仅为该特定用户创建 <b>room</b>

    假设当前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 发送/广播消息时,它只会被该用户接收。

    【讨论】:

    • HI。我怎样才能从课堂外向user_room_name 发送广播消息,比如view?谢谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-03
    • 1970-01-01
    相关资源
    最近更新 更多