简体   繁体   English

浏览器上的Django火警信号user_logged_out关闭

[英]Django fire signal user_logged_out on browser close

I'm working on a django application with a chat for users. 我正在为用户聊天的Django应用程序。 Therefore I need to present the status logged in or logged out to the other users. 因此,我需要向其他用户显示已登录或已注销的状态。 To accomplish this I used the signals environment of django. 为此,我使用了django的信号环境。 As long as the users are using the log out button everything works well. 只要用户使用注销按钮,一切都可以正常工作。 In case they are jut closing the browser or the tab there's no way to detect the status switch to offline. 如果他们正在关闭浏览器或选项卡,则无法检测到状态切换为脱机。 What is the best way to fire the user_logged_out signal, when the browser or tab gets closed? 当浏览器或选项卡关闭时,触发user_logged_out信号的最佳方法是什么?

generally it's not handled like this in chat applications. 通常,在聊天应用程序中不会像这样处理。 the way it's handled is that, you request a certain url from client at regular intervals. 它的处理方式是,您定期向客户端请求某个网址。 when your server is not getting any more request, it means that the user is offline. 当您的服务器再也没有收到请求时,表示该用户处于脱机状态。 the reason is simple. 原因很简单。 a lot of thinks can go wrong. 许多想法可能会出错。 what if user internet goes down? 如果用户互联网中断怎么办? how can you detect that? 你怎么能发现呢? so the best way is that you dedicate a certain url only for listening to such requests. 因此最好的方法是您仅将特定的URL用于侦听此类请求。 when requests stop. 当请求停止时。 it means that the user is offline. 这意味着用户处于离线状态。 in this case you don't care what happened, either user closed browser or internet stops or computer crashes or suddenly the computer turns off or etc... 在这种情况下,您无需担心发生了什么情况,无论是用户关闭的浏览器还是Internet停止或计算机崩溃,或者计算机突然关闭等。

you can trigger a signal like this: 您可以触发这样的信号:

from django.contrib.auth.signals import user_logged_in, user_logged_out 
from django.dispatch import receiver 
from django.conf import settings

@receiver(user_logged_in) 
def _user_logged_in(sender, user, request, **kwargs):
    ..........your code here.........

@receiver(user_logged_out) 
def _user_logged_out(sender, user, request, **kwargs):
    .......your code here.........

look at this_link for more detail. 查看this_link以获得更多详细信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM