简体   繁体   English

如何在django上关闭浏览器关闭会话

[英]How to kill a session on browser close in django

I am using Python- Django for my application. 我在我的应用程序中使用Python-Django。 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 当用户通过设置从浏览器中删除会话cookie来关闭浏览器时,Django会话提供使会话到期的机制

 SESSION_EXPIRE_AT_BROWSER_CLOSE=True

in settings.py file. 在settings.py文件中。 it deletes session cookie from user browser. 它从用户浏览器中删除会话cookie。 can I get this event on back end or in django? 我可以在后端或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. 或者如何通过ajax将消息传递给Django服务器,浏览器已关闭且会话cookie已被删除。 Tell me if it is possible by django or how can it be done using javascript 告诉我django是否有可能或者如何使用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: 为了在卸载之前进行ajax调用,我担心你会结束向用户显示一个恼人的警告框,因为它是事件所期望的:

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/ 请参阅django docs: https//docs.djangoproject.com/en/dev/ref/contrib/auth/#module-django.contrib.auth.signals此处http://docs.djangoproject.com/en/dev/专题/信号/

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

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