sending notification to one user using Channels 2

帅比萌擦擦* 提交于 2019-12-11 17:21:48

问题


I want to send notification to specific authenticated user using Channels 2.

In below code i am sending notification as a broadcast instead of that i want to send notification to a specific user.

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}")


回答1:


Most users new to Django-channels 2.x face this problem. let me explain.

self.channel_layer.group_add("gossip", self.channel_name) takes two arguments: room_name and channel_name

When you connect from your browser via socket to this consumer, you are creating a new socket connection called as channel. So, when you open multiple pages in your browser, multiple channels are created. Each channel has a unique Id/name : channel_name

room is a group of channels. If anyone sends a message to the room, all channels in that room will receive that message.

So, if you need to send a notification/message to a single user, then you must create a room only for that particular user.

Assuming that current user is passed in the consumer's 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
    )

Whenever you send/broadcast a message to user_room_name, It will only be received by that user.



来源:https://stackoverflow.com/questions/55310717/sending-notification-to-one-user-using-channels-2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!