【问题标题】:Django channel visitor counter realtimeDjango 频道访客计数器实时
【发布时间】:2020-12-17 07:10:10
【问题描述】:

我正在尝试使用 django 实时显示访客计数器。比如有多少访问者在我的网站上在线。

我编写了一个 websocket 消费者,但即使我在多个浏览器中打开该网站,它也总是给我 0。

这是我的 django 频道消费:

class VisitorConsumer(WebsocketConsumer):
    user_count = 0
    def connect(self):
        self.room_name = 'visitors'
        self.room_group_name = 'counter_%s' % self.room_name

        # Join room group
        async_to_sync(self.channel_layer.group_add)(
            self.room_group_name,
            self.channel_name
        )

         # Send message to room group
        async_to_sync(self.channel_layer.group_send)(
            self.room_group_name,
            {
                'type': 'send_visitor_count',
                'count': self.user_count
            }
        )

        self.accept()

    def disconnect(self, close_code):
        # Leave room group
        async_to_sync(self.channel_layer.group_discard)(
            self.room_group_name,
            self.channel_name
        )
       

    # Receive message from room group
    def send_visitor_count(self, event):
        count = event['count']

        # Send message to WebSocket
        self.send(text_data=json.dumps({
            'count': count
        }))

这是路由:

websocket_urlpatterns = [
    re_path(r'ws/visitors/$', consumers.VisitorConsumer),
]

我不明白为什么它总是触发 0。

谁能帮忙解决这个问题?

【问题讨论】:

    标签: django python-asyncio django-channels django-socketio


    【解决方案1】:

    我看不到您在哪里增加 user_count,但如果您增加它,即使增加它也可能不起作用,因为在不同工作人员中运行的不同消费者实例将无法访问相同的 user_count 变量。所以你应该将它存储在像 Redis 或 DB 这样的缓存中,并且不要忘记实际增加它

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-12-07
      • 1970-01-01
      • 1970-01-01
      • 2020-03-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多