Django-Channels 2 not persisting session data set in `connect`

独自空忆成欢 提交于 2019-12-11 05:30:02

问题


channels==2.1.2 | channels-redis==2.2.1 | daphne==2.2.0 | Django==1.11.6

I've upgraded to Channels 2 specifically for the ability to access and modify the session from within a consumer (and access it in a view), but that doesn't seem to be working. Basically, I want to identify AnonymousUsers and send them messages (each his own, not all of them together).

Here's my routing.py file:

application = ProtocolTypeRouter({
    # (http->django views is added by default)
    'websocket': AuthMiddlewareStack(
        URLRouter(
            core.routing.websocket_urlpatterns
        )
    ),
})

Here's my consumers.py file:

class ChatConsumer(WebsocketConsumer):
    def connect(self):
        if self.scope['user'].is_authenticated:
            user_id = str(self.scope['user'].id)
            self.scope['session']['user_identifier']= user_id
            self.group_name = user_id
        else:
            user_id = str(self.scope['user']) + str(uuid.uuid4())
            self.scope['session']['user_identifier'] = user_id
            self.group_name = user_id

        self.scope['session'].save()

        print(f" in consumer: {self.scope['session']['user_identifier']}")

        # Join room group
        async_to_sync(self.channel_layer.group_add)(
            self.group_name,
            self.channel_name
        )

        self.accept()

And in the view where I need to use send, I'm trying to get the group_name (user_identifier) from the session in case of an AnonymousUser:

def get_spotify_link(request):
    if request.user.is_authenticated:
        user_identifier = str(request.user.id)
    else:
        user_identifier = request.session['user_identifier']
        print(f"in get_spotify_link: {user_identifier}")

However, I'm intermittently (well, 99% of time) getting KeyError: 'user_identifier'.

Internal Server Error: /get_spotify_link/
Traceback (most recent call last):
  File "/Users/myusername/.virtualenvs/bap_dev/lib/python3.6/site-packages/django/core/handlers/exception.py", line 41, in inner
    response = get_response(request)
  File "/Users/myusername/.virtualenvs/bap_dev/lib/python3.6/site-packages/django/core/handlers/base.py", line 187, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "/Users/myusername/.virtualenvs/bap_dev/lib/python3.6/site-packages/django/core/handlers/base.py", line 185, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/Users/myusername/PycharmProjects/artist_notify/core/views.py", line 442, in get_spotify_link
    user_identifier = request.session['user_identifier']
  File "/Users/myusername/.virtualenvs/bap_dev/lib/python3.6/site-packages/django/contrib/sessions/backends/base.py", line 57, in __getitem__
    return self._session[key]
KeyError: 'user_identifier'
[2018/07/08 20:54:03] WebSocket HANDSHAKING / [127.0.0.1:65478]
 in consumer: AnonymousUser8883761c-f673-413e-82e2-413d1cbb17e3
[2018/07/08 20:54:03] WebSocket CONNECT / [127.0.0.1:65478]
Internal Server Error: /get_spotify_link/
Traceback (most recent call last):
  File "/Users/myusername/.virtualenvs/bap_dev/lib/python3.6/site-packages/django/core/handlers/exception.py", line 41, in inner
    response = get_response(request)
  File "/Users/myusername/.virtualenvs/bap_dev/lib/python3.6/site-packages/django/core/handlers/base.py", line 187, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "/Users/myusername/.virtualenvs/bap_dev/lib/python3.6/site-packages/django/core/handlers/base.py", line 185, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/Users/myusername/PycharmProjects/artist_notify/core/views.py", line 442, in get_spotify_link
    user_identifier = request.session['user_identifier']
  File "/Users/myusername/.virtualenvs/bap_dev/lib/python3.6/site-packages/django/contrib/sessions/backends/base.py", line 57, in __getitem__
    return self._session[key]
KeyError: 'user_identifier'

来源:https://stackoverflow.com/questions/51236316/django-channels-2-not-persisting-session-data-set-in-connect

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!