channels
channels copied to clipboard
self.scope['session'] doesn't save the data (channels==2.2.0)
channels: 2.2.0 django: 2.2.4 channels-redis: 2.4.0
routing.py:
application = ProtocolTypeRouter(
{"websocket": AuthMiddlewareStack(URLRouter(websocket_routes))}
)
consumers.py:
class ExportConsumer(JsonWebsocketConsumer):
def connect(self):
self.accept()
if not self.scope['session'].get('something'):
self.scope['session']['something'] = 0
else:
self.scope['session']['something'] += 1
self.scope['session'].save()
Session doesn't save the data, whatever I do. What is wrong?
I have encountered the same problem and have posted a StackOverflow question. This is core functionality without which my app will not work correctly. Would appreciate if @hishnash would take a look at my SO question since he answered a similar question here.
In follow up to my above comment, @hishnash provided an answer to my StackOverflow question. This appears to be a bug in Django Channels. @chapkovski, would you consider changing the title of this issue to: BUG: self.scope['session'] doesn't save the data (channels==2.2.0)?
To be clear you can/should absolutly be able to save a session data to an existing session.
To ensure the user has an exisiting session you ws client should load a regular endpoint on your server first, see djangos https://docs.djangoproject.com/en/3.0/topics/http/sessions/#module-django.contrib.sessions for deatils about using anonymous sessions. The trick will be ensuring your session ID does not change when you login
the user/save data, you will of cource need to be using server side session data storage.
Your above issue is you cant issue a session cookie on the upgrade
response. My understanding is there is some uncertianty if ws-clients will even respect Set-Cookie
headers on ws-upgrade.
There have been a few other issues opened in the past that releate to this idea of setting cookies in the connect handshake, https://github.com/django/channels/issues/917 has some context on why this is not supported.
@hishnash Yes, I was able to set the session cookie from the Django view, and that pretty much does what I need it to. If saving the session cookie doesn't work from Channels, then that portion of the docs should be changed. Thanks for your help!