整个网站上使用了一个Django Channels websocket使用者吗?

时间:2019-05-12 06:53:56

标签: javascript python django websocket django-channels

我有一个使用WebSockets和一个使用者(ChatConsumer)进行应用程序的聊天和通知部分的Django项目。

我将routing.py设置为url(r"^messages/(?P<username>[\w.@+-]+)", ChatConsumer),但是由于通知也取决于websocket,因此需要从网站上的任何页面进行访问。

原因是,当用户单击通知时,使用

将其标记为read

socket.send(JSON.stringify(data));

现在,通知仅在用户位于/messages/<username>/ URL上时有效。

如果我更改routing.py以解决整个网站(url(r"^", ChatConsumer)),显然会遇到问题

File "./consumers.py" in websocket_connect
    other_user = self.scope['url_route']['kwargs']['username']
  'username' 

有解决这个问题的简单方法吗?因为如果我错了就纠正我,但是由于通知和聊天紧密地纠缠在一起,所以我认为写一个新的用户不合适吗?

consumers.py

class ChatConsumer(AsyncConsumer):
    async def websocket_connect(self, event):

        other_user = self.scope['url_route']['kwargs']['username']
        me = self.scope['user']
        thread_obj = await self.get_thread(me, other_user)
        self.thread_obj = thread_obj
        chat_room = f"thread_{thread_obj.id}"
        self.chat_room = chat_room
        # below creates the chatroom
        await self.channel_layer.group_add(
            chat_room,
            self.channel_name
        )

        await self.send({
            "type": "websocket.accept"
        })

    async def websocket_receive(self, event):
        # when a message is recieved from the websocket
        print("receive", event)

        message_type = json.loads(event.get('text','{}')).get('type')
        if message_type == "notification_read":
            user = self.scope['user']
            username = user.username if user.is_authenticated else 'default'
            # Update the notification read status flag in Notification model.
            notification = Notification.objects.filter(notification_user=user).update(notification_read=True)
            print("notification read")
            return

        front_text = event.get('text', None)
        if front_text is not None:
            loaded_dict_data = json.loads(front_text)
            msg =  loaded_dict_data.get('message')
            user = self.scope['user']
            username = user.username if user.is_authenticated else 'default'
            notification_id = 'default'
            myResponse = {
                'message': msg,
                'username': username,
                'notification': notification_id,
            }
            print(myResponse)
            await self.create_chat_message(user, msg)
            other_user = self.scope['url_route']['kwargs']['username']
            other_user = User.objects.get(username=other_user)
            await self.create_notification(other_user, msg)

            # broadcasts the message event to be sent, the group send layer
            # triggers the chat_message function for all of the group (chat_room)
            await self.channel_layer.group_send(
                self.chat_room,
                {
                    'type': 'chat_message',
                    'text': json.dumps(myResponse)
                }
            )

    # chat_method is a custom method name that we made
    async def chat_message(self, event):
        # sends the actual message
        await self.send({
                'type': 'websocket.send',
                'text': event['text']
        })

    async def websocket_disconnect(self, event):
        # when the socket disconnects
        print('disconnected', event)

    @database_sync_to_async
    def get_thread(self, user, other_username):
        return Thread.objects.get_or_new(user, other_username)[0]

    @database_sync_to_async
    def create_chat_message(self, me, msg):
        thread_obj = self.thread_obj
        return ChatMessage.objects.create(thread=thread_obj, user=me, message=msg)

    @database_sync_to_async
    def create_notification(self, other_user, msg):
        last_chat = ChatMessage.objects.latest('id')
        created_notification = Notification.objects.create(notification_user=other_user, notification_chat=last_chat)
        return created_notification

base.html

<script>
    $(document).ready(function() {
      // $('div[id^="notification-"]')
      $("#notificationLink").click(function() {
        $('span[id^="notification"]').each(function() {
          var username = '{{ request.user.username }}'
          var data = {
            "type": "notification_read",
            "username": username,
          }
          socket.send(JSON.stringify(data));
        });
    });
  </script>

<script>
...
    var endpoint = wsStart + loc.host + loc.pathname
    var socket = new ReconnectingWebSocket(endpoint)
    // all the websocket scripts - client side*
...
</script>

1 个答案:

答案 0 :(得分:0)

我认为您应该向other_user发送消息,所以应该是这样

2019-05-10 13:24:20.686  INFO 696 --- [DBProcessThread] c.c.sz_vss.demo.AbstractSave2DBProcess   : Stock save 2 DB batch size: 2000
2019-05-10 13:24:22.963  INFO 696 --- [DBProcessThread] c.c.sz_vss.demo.AbstractSave2DBProcess   : Save Stock data 2 DB successfully
2019-05-10 13:24:24.113  INFO 696 --- [DBProcessThread] c.c.sz_vss.demo.AbstractSave2DBProcess   : Save Stock data 2 CCXE DB successfully
--
2019-05-10 13:24:24.113  INFO 696 --- [DBProcessThread] c.c.sz_vss.demo.AbstractSave2DBProcess   : Stock save 2 DB batch size: 2000
2019-05-10 13:24:23.710  INFO 696 --- [DBProcessThread] c.c.sz_vss.demo.AbstractSave2DBProcess   : Save Stock data 2 DB successfully
2019-05-10 13:24:24.103  INFO 696 --- [DBProcessThread] c.c.sz_vss.demo.AbstractSave2DBProcess   : Save Stock data 2 CCXE DB successfully
--
2019-05-10 13:24:24.103  INFO 696 --- [DBProcessThread] c.c.sz_vss.demo.AbstractSave2DBProcess   : Stock save 2 DB batch size: 2000
2019-05-10 13:24:26.595  INFO 696 --- [DBProcessThread] c.c.sz_vss.demo.AbstractSave2DBProcess   : Save Stock data 2 DB successfully
2019-05-10 13:24:26.963  INFO 696 --- [DBProcessThread] c.c.sz_vss.demo.AbstractSave2DBProcess   : Save Stock data 2 CCXE DB successfully

因此您不再需要使用self.scope ['url_route'] ['kwargs'] ['username']
顺便说一句,您可以在github上共享代码吗,因为我准备做这样的事情,并且我认为您的项目会大大帮助我