Home > Mobile >  Need help accessing session variables in Django Channels consumers.py
Need help accessing session variables in Django Channels consumers.py

Time:02-17

I am generating a random userid and storing it as a session variable in my view. I am trying to access that session variable in consumers.py to identify the user (not authenticated ) and update the user about the changes in the database.

view.py :

def index(request):
        request.session['uniqueid'] = 'random_number'
        print(request.session['uniqueid']) # this is working 
    return render(
        request,
        'home.html',
    )

consumers.py:

class WSConsumer(WebsocketConsumer):
    def connect(self):
        self.accept()
        U = self.scope['session']["uniqueid"]

Error:

Exception has occurred: KeyError (note: full exception trace is shown but execution is paused at: connect) 'uniqueid'

I changed localhost to 127.0.0.1 ('ws://127.0.0.1:8000/ws/socket/') as described in https://stackoverflow.com/a/67242832, but receive the same error.

I am unable to pin down the error, any help would be appreciated.

CodePudding user response:

You should mark the session as "modified" to make sure it gets saved.

Indeed SessionMiddleware check if request.session was modified, or if the configuration is to save the session every time, save the changes and set a session cookie or delete the session cookie if the session has been emptied.

def index(request):
        session = request.session 
        session['uniqueid'] = 'random_number'
        session.modified = True  
    return render(request, 'home.html')

Also print in your view function return cached value nor pesistent value.

  • Related