Search code examples
pythondjangowebsocketdjango-channels

Does Django Channels create a new consumer with every use?


I have a consumer

class BingoConsumer(WebsocketConsumer):
    logged_in = 0

    def connect(self):
        async_to_sync(self.channel_layer.group_add)(
            "login", self.channel_name
        )
        self.accept()

    def disconnect(self, close_code):
        async_to_sync(self.channel_layer.group_discard)(
            "login", self.channel_name
        )
        self.logged_in -= 1
    def receive(self, text_data):
        text_data = json.loads(text_data)
        if text_data['type'] == 'login':
            self.logged_in += 1
            async_to_sync(self.channel_layer.group_send)(
                "login", {
                    'type': 'login',
                    'count': self.logged_in,
                }
            )

    def login(self, event):
        self.send(text_data=json.dumps({
            'type': 'login',
            'total': event['count'],
        }))

Which gets called every time a user logs in to my website, it'll automatically call the websocket with type 'login'. I want to track the amount of users currently logged in, but currently no matter how many people are logged in, it remains 1. Which makes me wonder, does Django consider a consumer to be single use class? Does it create them and destroy them as needed?


Solution

  • variables are not shared among different sessions. If you want to calculate variables in multiple sessions, you probably need to use database or local file.