简体   繁体   中英

Send notification to a specific user by django channel

X and Y are two Person s. X sends a friend request to Y so in Y s profile there will be a notification of friend request. Then Y accept the Friend request so in X profile also be appeared a notification of accepting friend request.

I know real time notification can be handle by Django channel and it will be solve by creating group by user.

But is it best practice to create group for every particular user? Is there another way to solve this problem?

The easiest way to send a message to an individual user is to add that user to their own group on your consumer's connect() method.

class Consumer(WebsocketConsumer):
    def connect(self):
        self.group_name = self.scope['user'].pk

        # Join group
        async_to_sync(self.channel_layer.group_add)(
            self.group_name,
            self.channel_name
        )
        self.accept()

Every time a user visits a page specified in yourapp.routing.websocket_urlpatterns they'll be automatically added to the group so there isn't much work to do.

Sending the message is also easy because you already have both target user.pk s required for the messages.

def ajax_accept_friend_request(request):
    friend = request.GET.get('id', None)
    channel_layer = get_channel_layer()

    # Trigger message sent to group
    async_to_sync(channel_layer.group_send)(
        friend,
        {
            'type': 'your_message_method',
            'accept': True
        }
    )
    return HttpResponse()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM