如何拒绝和关闭 django-channels 2 中的连接?

How can I reject and close connections in django-channels 2?

我开始使用 django-channels 已经 1 个月了,现在我感觉我没有正确断开 websockets。 当我断开连接时,如果没有人在那里,我想完全摧毁这个群体,它应该没有存在的迹象。 当我拒绝连接时,我提高 channels.exceptions.DenyConnection 或发送 {'accepted': 'False'} 我只是想知道这是否是做我提到的事情的正确方法。

据我了解,关闭群组的方法是使用 group_discard。

def disconnect(self, close_code):
    async_to_sync(self.channel_layer.group_discard)("yourgroupname", self.channel_name)

如果没有对此进行测试,我会假设引发异常会导致客户端出现错误 500。收到错误的客户端可能会将其解释为不是 "closed normally".

在此处查看频道文档:https://channels.readthedocs.io/en/latest/topics/channel_layers.html#groups

尝试调用 self.close()

From the channels Documentation:

class MyConsumer(WebsocketConsumer):

    def connect(self):
        # Called on connection.
        # To accept the connection call:
        self.accept()
        # Or accept the connection and specify a chosen subprotocol.
        # A list of subprotocols specified by the connecting client
        # will be available in self.scope['subprotocols']
        self.accept("subprotocol")
        # To reject the connection, call:
        self.close()