Search code examples
pythondjangowebsocketdjango-channelsdisconnect

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


It's been 1 month since I started using django-channels and now I have a feeling that I am not disconnecting websockets properly. When I disconnect I want to destroy the group completely if no one is there and it should be no sign of existence. When I'm rejecting connections I raise channels.exceptions.DenyConnection or send {'accepted': 'False'} I was just wondering if this is the right way to do things that I've mentioned or not.


Solution

  • As far as I've understood this, the way to close a group is by using group_discard.

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

    Without having tested this, I would assume that raising an exception would result in an error 500 at the client. And a client receiving an error would probably interpret that not as "closed normally".

    See channel docs here: https://channels.readthedocs.io/en/latest/topics/channel_layers.html#groups