Django频道设置自定义channel_name

问题描述 投票:0回答:1

我正在使用Django通道,并且能够使用提供的内置channel_name正确连接和发送消息。我想知道是否有一种方法可以在Web套接字连接中更改和注册自定义channel_name。我尝试更改它,但channel_layer alredy存储了内置的channel_name,但无法发送消息。

这是提供的测试课程

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。因此,这就是为什么我要强制使用自己的频道名称的原因。

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

django django-channels
1个回答
0
投票

频道名称由您的频道层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!"},
)
© www.soinside.com 2019 - 2024. All rights reserved.