channels icon indicating copy to clipboard operation
channels copied to clipboard

self.scope['session'] doesn't save the data (channels==2.2.0)

Open chapkovski opened this issue 4 years ago • 4 comments

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?

chapkovski avatar Mar 08 '20 03:03 chapkovski

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.

DanielSwain avatar Jun 05 '20 01:06 DanielSwain

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)?

DanielSwain avatar Jun 05 '20 12:06 DanielSwain

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 avatar Jun 05 '20 21:06 hishnash

@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!

DanielSwain avatar Jun 05 '20 21:06 DanielSwain