我想做的是在用户从另一个选项卡注销时断开 websocket 连接。所以,我在 django 频道中使用
get_user()
来检查用户是否仍然登录(在会话中)。
我同时打开了多个标签页。我从其中一个选项卡注销了。但是,注销后,它仍然显示
user.is_authenticated = True
,我可以从self.scope["user"]
获得用户。
我的代码有什么问题?
这是我的代码。 在 views.py
中from django.contrib.auth.views import LogoutView
...
class Logout(LogoutView):
template_name = "account/logout.html" # log user out
在cousumers.py中
from asgiref.sync import async_to_sync
from channels.generic.websocket import JsonWebsocketConsumer
class Chat(JsonWebsocketConsumer):
...
def receive_json(self, content, **kwargs):
message = content['message']
user = async_to_sync(get_user)(self.scope)
logging.info(user.is_authenticated) # still true after logging out
logging.info(f'user is {self.scope["user"]}') # show the user as well
if user is None:
return self.disconnect()
self.send_json(content={'message': f'receive: {message}'})
...
我检查了
django
和django-channels
的文档和源文件,并尝试在logout
使用channels.auth
的consumers.py
。它有效,但不是我想要使用的。我希望我可以在没有用户状态的情况下获得正确的会话。