Django 频道设置自定义 channel_name

Django Channels setting custom channel_name

我正在使用 Django 频道,我能够使用提供的内置 channel_name 正确连接和发送消息。 我想知道是否有办法在网络套接字连接中更改和注册自定义 channel_name。 我尝试更改它,但 channel_layer 已存储内置 channel_name,我无法发送消息。

这是提供的测试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']
        }))

这是我发送消息的方式:

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

我阅读了文档并将 channel_name 存储在 db 中,但每次我执行连接时,该名称都会更改。我想避免更新调用淹没 db。 所以这就是为什么我要强制使用自己的频道名称。

有办法改变它还是只是浪费时间?

频道名称被您的频道层删除https://github.com/django/channels/blob/580499752a65bfe4338fe7d87c833dcd5d4a3939/channels/layers.py#L259 https://github.com/django/channels/blob/580499752a65bfe4338fe7d87c833dcd5d4a3939/channels/consumer.py#L46

所以我建议使用 group 这个你可以设置任何你喜欢的名字。

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!"},
)