Django频道:使用使用者无法登录到会话

时间:2019-07-10 05:24:44

标签: django django-channels django-sessions

我有一个使用django频道和Vue作为前端构建的SPA。

用户首次加载网页时,使用

提供index.html
url(r'^.*$', TemplateView.as_view(template_name='index.html'), name="app")

然后前端使用Web套接字与服务器通信。

发送的消息之一可能是使用适当的凭据登录到系统。

我一直按照https://channels.readthedocs.io/en/latest/topics/authentication.html上的说明进行操作,以通过使用者登录。

class MyConsumer(AsyncJsonWebsocketConsumer):

    async def connect(self):
        self.group_name = str(uuid.uuid1())
        print(self.scope['session'].session_key)
        self.user = self.scope["user"]

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

        await self.accept()

        # User data
        await self.send(simplejson.dumps(dict(data=dict(socketid=self.group_name, user=dict(username=self.user.username or None)))))

    async def receive_json(self, jsdata):       
        kwargs = jsdata.get('kwargs', {})

        # Manage Login
        if is_login_message(jsdata): # This checks if the message is sent to do login
            user = authenticate(**kwargs)
            await login(self.scope, user)
            print('Saving login session')
            await database_sync_to_async(self.scope["session"].save)()
            await self.send(simplejson.dumps(dict(data=dict(user=dict(username=user.username)))))
            print(self.scope['session'].session_key)
            return

一切正常。当用户登录时,我可以看到该热键已被打印。但是,当我重新加载网页时,该会话未保留。它在 connect 方法中显示“无”。我看到登录完成后未设置cookie。我希望运行以下行以在浏览器中设置一些cookie时,从服务器发送到客户端的信息。

            await database_sync_to_async(self.scope["session"].save)()
            await self.send(simplejson.dumps(dict(data=dict(user=dict(username=user.username)))))

但是这没有发生。可能是什么问题?

0 个答案:

没有答案
相关问题