Django channel visitor counter realtime

582 views Asked by At

I am trying to show visitor counter on realtime basis with django. like how many visitor are online at my webiste.

I written a websocket consumer but it alwasy give me 0 even if i open the site in multiple browser.

this is my django channel consume:

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
        }))

adn this is the routing:

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

I am not getting why it's always firing 0.

Can anyone help to fix this?

1

There are 1 answers

0
Ken4scholars On BEST ANSWER

I don't see where you are incrementing the user_count but even that may not work if you incremented it because the different instances of the consumer running in different workers won't have access to the same user_count variable. So you should store it in a cache like Redis or DB and don't forget to actually increment it