Search code examples
djangodjango-channels

Django Channels - execute something when a WebSocket is "closed"


I'm using WebsocketConsumer, and storing data user-related on the cache layer

And when the WebsocketConsumer disconnected, I clean everything related to the user

from channels.generic.websocket import WebsocketConsumer


class MyConsumer(WebsocketConsumer):

    def connect(self):
        self.store_session_data()

    def disconnect(self, _):
        self.clean_session_data()

The problem is, if either the browser's tab, or the browser itself is closed, disconnect won't be triggered

Question

Is there a way to execute something no matter how the WebsocketConsumer is closed?

Any thought?


Solution

  • Using websocket_disconnect along side with disconnect, I was able to properly clean the session data no matter how the connection was closed

    class MyConsumer(WebsocketConsumer):
    
        def connect(self):
            self.store_session_data()
    
        def disconnect(self, _):
            self.clean_session_data()
    
        def websocket_disconnect(self, message):
            self.clean_session_data()
            super().websocket_disconnect(message)
    

    Update: calling super().websocket_disconnect(message) is required to proper disconnect