简体   繁体   中英

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

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM