【问题标题】:Send notification to a specific user by django channel通过 django 频道向特定用户发送通知
【发布时间】:2018-11-23 07:03:08
【问题描述】:
X 和 Y 是两个 Persons。 X 向Y 发送好友请求,因此在Ys 个人资料中会有好友请求通知。然后Y接受好友请求,所以在X个人资料中也会出现接受好友请求的通知。
我知道实时通知可以由 Django 频道处理,它将通过按用户创建组来解决。
但是为每个特定用户创建组是最佳做法吗?有没有其他方法可以解决这个问题?
【问题讨论】:
标签:
python
django
django-channels
【解决方案1】:
向单个用户发送消息的最简单方法是通过消费者的connect() 方法将该用户添加到他们自己的组中。
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()
每次用户访问yourapp.routing.websocket_urlpatterns 中指定的页面时,他们都会自动添加到组中,因此无需做太多工作。
发送消息也很容易,因为您已经拥有消息所需的两个目标user.pks。
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()