Home > OS >  access django channels' consumer class variables from outside
access django channels' consumer class variables from outside

Time:09-30

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

CodePudding user response:

You can get all instance with gc.get_objects

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)
  • Related