从 Django Channels 组中删除特定用户?

Remove a specific user from a Django Channels group?

我有几个 Django 频道组,我用它们向客户端发送各种消息。

我能否仅使用我要删除的用户的 ID 从这些组中删除特定用户?

另一个可能的选择是仅使用用户的 ID 强制断开用户的连接。

您需要在消费者 connect 方法中阻止基于 scope['user'] 的连接,如下所示:

class MyConsumer(AsyncJsonWebsocketConsumer):

    async def connect(self):
        id_cannot_connect = 1
        if self.scope['user'] == id_cannot_connect:
            await self.close()
        else:
            await self.accept()

如果您想创建允许连接到特定群组的用户列表,您需要在数据库中存储群组和群组用户,并以与上述 connect 方法相同的方式使用它。

编辑:您可以从 receive_json 中带有 group_discard 的组中删除用户的频道,您仍然可以访问 self.scope['user'] 以过滤所需的用户。

我最终解决了这个问题,方法是在频道连接上存储每个频道名称 (self.channel_name),并在断开连接时删除它们。然后将它们绑定到 Django 用户对象。

现在,如果我想从一个组中删除一个用户,我可以遍历所有存储的与用户对象相关的频道名称,然后 运行 group_discard.

关于这个问题我想了几天,知道如何实现,但目前无法测试。您应该尝试像这样更改 receive() method

async def receive(self, text_data=None, bytes_data=None):
        text_data_json = json.loads(text_data)
        message = text_data_json['message']
        users_to_kick = text_data_json['kick']

        # you should inspect scope['user'] cuz I am not sure in what place
        # user's id is placed, but there is 'user' object.
        if self.scope['user']['id'] in list(map(int, users_to_kick)):
            await self.close()
        else:
            await self.channel_layer.group_send(
                self.room_group_name,
                {
                    'type': 'some_method',
                    'message': message
                 }
             )

你必须启用授权系统,你不能踢匿名用户。并且您必须从前端发送您要踢出的用户列表。

首先,您必须将用户的channel_name保存到他们的模型

我们假设您也有 group_name 个频道

然后您可以使用 group_discard 从组中删除用户,如下所示:

group_name = 'name_of_channels_group'
user = User.objects.get(id=id)
channel_name = user.channel_name
async_to_sync(self.channel_layer.group_discard)(group_name, channel_name)

https://channels.readthedocs.io/en/stable/topics/channel_layers.html?highlight=group_send#groups