简体   繁体   中英

Django fire signal user_logged_out on browser close

I'm working on a django application with a chat for users. 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. 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?

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. 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...

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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