使用Django频道进行通知

时间:2019-05-14 14:33:58

标签: django notifications django-channels

我正在研究一个django项目,该项目允许两个用户一起聊天。收到新消息后,您会收到通知。为了完成这两个任务,我正在使用Django通道并打开一个websocket。在我的聊天应用程序按预期工作的同时,我继续进行通知部分的工作。但是,那是我面临的一些问题。

我有一个signal.py,无论何时创建通知,我都会将其发送给用户房间。

signals.py

@receiver(post_save, sender=Notification)
def newNotification(sender, instance, created, **kwargs):
    if created:

        channel_layer = get_channel_layer()
        room_name = "notif_room_for_user_"+str(instance.targetUser.id)

        async_to_sync( channel_layer.group_send)(
                   room_name, {"type": "user.gossip",
                   "event": instance.objectName,
                   "targetUser": instance.targetUser}
        )

consumers.py

class NoseyConsumer(AsyncJsonWebsocketConsumer):

async def connect(self):

    self.user = self.scope["user"]
    self.user_room_name = "notif_room_for_user_"+str(self.user.id) 

    await self.channel_layer.group_add(
            self.user_room_name,
            self.channel_name
        )
    await self.accept()


async def disconnect(self, close_code):
    await self.channel_layer.group_discard(
            self.user_room_name, 
            self.channel_name
            )


async def user_gossip(self, event):
    await self.send_json(event)

当我打开网页时,websocket正常连接。问题是当我发送消息并创建新通知时,出现以下错误

 "You cannot use AsyncToSync in the same thread as an async event loop - "
 You cannot use AsyncToSync in the same thread as an async event loop - just await the async function directly.

该错误之后,我将signal.py中的newNotification更改为async。但是然后,它永远不会被调用。

0 个答案:

没有答案
相关问题