简体   繁体   中英

How to kill a session on browser close in django

I am using Python- Django for my application. I want to kill the session when a user close his browser and want to store that session killing or browser closing time in database.
Django sessions provide mechanism to expire session when a user close browser by deleting session cookie from the browser by setting

 SESSION_EXPIRE_AT_BROWSER_CLOSE=True

in settings.py file. it deletes session cookie from user browser. can I get this event on back end or in django? or how can I pass a message to Django server by ajax that the browser has been closed and session cookie has been deleted. Tell me if it is possible by django or how can it be done using javascript

In order to make an ajax call before unload I am afraid you will end showing an annoying alert box to the user as its what the event expects:

Date.prototype.timeNow = function(){
     return ((this.getHours() < 10)?"0":"") + this.getHours() +":"+ ((this.getMinutes() < 10)?"0":"") + this.getMinutes() +":"+ ((this.getSeconds() < 10)?"0":"") + this.getSeconds();
};

$(window).bind("beforeunload", function (e) {
    var timeNow = new Date().timeNow(); 
    $.post( "api/closingTime", { "closingTime": timeNow } );
    return "Thanks for your visit";
});   

which is also a little problematic as if the user decides to click to stay on the page the post request still goes ahead

You can use a signal like this

  from django.contrib.auth.signals import user_logged_out


  def do_stuff(sender, user, request, **kwargs):
      whatever...

  user_logged_out.connect(do_stuff)

See django docs: https://docs.djangoproject.com/en/dev/ref/contrib/auth/#module-django.contrib.auth.signals and here http://docs.djangoproject.com/en/dev/topics/signals/

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