Search code examples
djangodjango-channelsconsumer

access django channels' consumer class variables from outside


class ExampleConsumer(AsyncWebsocketConsumer):

    async def connect(self):
        self.id = 1
        self.foo = 'bar'
        await self.accept()

Is it possible to get all existing instances of ExampleConsumer, filter them by id and get foo value? Somewhere in a django view


Solution

  • You can get all instance with gc.get_objects so:

    import gc
    
    class ExampleConsumer(AsyncWebsocketConsumer):
    
        async def connect(self):
            self.id = 1
            self.foo = 'bar'
            await self.accept()
    
    
    def get_inc(cls):
        return [obj for obj in gc.get_objects() if isinstance(obj, cls)]
    
    for i in get_inc(ExampleConsumer):
        print(i.foo)