[Answered ]-Get updated session data in a Django Channels' consumer

1👍

While searching for the solution I found some unanswered questions discussing the same problem. And it doesn’t seem to be covered in the docs (maybe it’s mentioned somewhere, but I didn’t manage to find it), so I decided to post my solution. Please comment if it’s not correct for some reason.

For example, you want to get the updated session data inside receive method of an AsyncWebsocketConsumer child class.

class MyConsumer(AsyncWebsocketConsumer):
async def receive(self, data):
   current_session_data = await sync_to_async ( self.scope["session"].load) ()

load returns a dict with all the session variables.
self.scope["session"] is not a dict, but it has update method which updates the underlying dict:

self.scope['session'].update( current_session_data )
await sync_to_async ( self.scope["session"].save ) ()

Hope this helps someone

Leave a comment