Search code examples
djangodjango-channels

Django Channels setting custom channel_name


I'm using Django channels and I'm able to properly connect and send message with builtin channel_name provided. I'm wondering if there is a way to change and register a custom channel_name within web socket connection. I tried changing it but channel_layer alredy stored builtin channel_name and I'm unable to send a message.

This is a provided test class

class TestWebSocket(AsyncWebsocketConsumer): 
   async def connect(self):
        self.channel_name = "custom.channelname.UNIQUE"
        await self.accept()

   async def test_message(self, event):
        await self.send(text_data=json.dumps({
            'message': event['message']
        }))

Here how I send a message:

async_to_sync(channel_layer.send)('custom.channelname.UNIQUE',
                                  {'type': 'test.message', 'message': 'dfdsdsf'})

I read documentation and it stores channel_name inside db, but each time I perform a connection, that name will change. I want to avoid flooding db with update calls. So this is why I'm trying to force my own channel names.

There is a way to change it or is oly waste of time?


Solution

  • The channel name is deseided by your channel layer https://github.com/django/channels/blob/580499752a65bfe4338fe7d87c833dcd5d4a3939/channels/layers.py#L259 https://github.com/django/channels/blob/580499752a65bfe4338fe7d87c833dcd5d4a3939/channels/consumer.py#L46

    so I would instead suggest using a group this you can setup with any name you like.

    https://channels.readthedocs.io/en/latest/topics/channel_layers.html#groups

    class TestWebSocket(AsyncWebsocketConsumer): 
       async def connect(self):
            await self.channel_layer.group_add(
                "custom.channelname.UNIQUE",
                self.channel_name
            )
            self.groups.append("custom.channelname.UNIQUE") # important otherwise some cleanup does not happened on disconnect.
            await self.accept()
    
       async def test_message(self, event):
            await self.send(text_data=json.dumps({
                'message': event['message']
            }))
    
    
    # to send to that group
    await channel_layer.group_send(
        "custom.channelname.UNIQUE",
        {"type": "test.message", "message":"Hello!"},
    )