Search code examples
djangodjango-channels

Django-Channels: How to get channel_name from user_id?


Below code prints the channel_name of a client

class ChatConsumer(WebsocketConsumer):
    def connect(self):
        self.room_name = self.scope['url_route']['kwargs']['room_name']
        self.room_group_name = 'chat_%s' % self.room_name
        print(self.channel_name)

How to get the channel_name from user_id (user.id) for an authenticated user (It needs to be accessed outside the consumer)? Something like below

import foo
channel_name=foo.get_channel_name_from_user_id(user_id)
print(channel_name)

Thanks! Happy new year!


Solution

  • The self.channel_name is not associated to the user-class but to "AsyncWebsocketConsumer";
    If you want you can totally specify the channel_name based on the user_id by explicitly defining the channel-layer name as such

    async def connect(self):
        user = self.scope['user']
    
        if user.is_anonymous:
            print("user was unknown")
            await self.close()
        else:
            await self.channel_layer.group_add(
                group=self.doc_pat_grp_id,
                channel=user.id#the channel-name
            )
            await self.accept()
    

    Using Channel-layer outside of consumer

    #The python code; like you mentioned above.
    import foo
    from django.contrib.auth import get_user_model
    from channels.layers import get_channel_layer
    from asgiref.sync import async_to_sync 
    #since django runs synchronously and channel_layer runs asynchronous 
    #we need to explicitly tell channel_layer to run it in synchronous
    
    user = get_user_model()
    channel_layer = get_channel_layer()
    print(channel_layer)