Django会话在浏览器关闭时或过期后到期 [英] Django session expires at browser close OR after time

查看:244
本文介绍了Django会话在浏览器关闭时或过期后到期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Django文档指出:


您可以控制会话框架使用浏览器长度的
会话还是持久性会话



如果将SESSION_EXPIRE_AT_BROWSER_CLOSE设置为True,则Django将使用
个浏览器长度的cookie,这些cookie会尽快过期用户
关闭其浏览器。如果希望人们每次打开浏览器都必须登录
,请使用此选项。



此设置是全局默认设置,可以用$覆盖。通过在视图中使用会话中如上所述显式调用
request.session的set_expiry()方法,可以在每个会话级别达到b $ b。


因此,当我在设置文件中将SESSION_EXPIRE_AT_BROWSER_CLOSE设置为True时,这确实是它的工作。这很好,因为我希望用户的会话在浏览器关闭时过期。但是,我也希望用户的会话在闲置15分钟后过期。如果我使用上面提到的set_expiry(),则SESSION_EXPIRE_AT_BROWSER_CLOSE将被覆盖,因此,如果用户关闭浏览器,然后在到期前重新打开浏览器,则该会话仍然有效。不是我想要的东西。 > 。实际上不是真的。无论我的用户是否在网站上单击,它都会过期。



因此,总而言之,我想做的是:


  1. 已将我的会话配置为:如果用户关闭浏览器,则该会话会自动过期。

  2. 设置会话有效期长度会根据活动进行更新,即,如果用户在网站上进行其他操作,则会重置过期。

想法/建议?

解决方案

正如Jiaaro在此答案,您可以使用 SESSION_EXPIRE_AT_BROWSER_CLOSE 并在每次请求时为会话设置时间戳,并添加自定义中间件来处理不活动状态。


The Django documentation states:

You can control whether the session framework uses browser-length sessions vs. persistent sessions with the SESSION_EXPIRE_AT_BROWSER_CLOSE setting.

If SESSION_EXPIRE_AT_BROWSER_CLOSE is set to True, Django will use browser-length cookies -- cookies that expire as soon as the user closes his or her browser. Use this if you want people to have to log in every time they open a browser.

This setting is a global default and can be overwritten at a per-session level by explicitly calling the set_expiry() method of request.session as described above in using sessions in views.

So when I set SESSION_EXPIRE_AT_BROWSER_CLOSE to True in my settings file, this indeed is what it does. This is good because I want a user's session to expire upon browser close. However, I also want a user's session to expire after, say, 15 minutes of inactivity. If I use set_expiry() mentioned above, the SESSION_EXPIRE_AT_BROWSER_CLOSE is overridden so if a user closes the browser and then re-opens the browser before the expiration, the session is still valid. Not what I want.

In addition, the documentation for set_expiry() says the sessions expires after the set amount of time of inactivity. That's actually not true. It expires no matter what, whether my user is clicking around on the site or not.

So to summarize, what I want to do is:

  1. Have my sessions configured that if the user closes the browser, the session automatically expires.
  2. Set a session expiration length that is updated with activity, i.e. if a user does something else on the site, the expiration is reset.

Thoughts/suggestions?

解决方案

As Jiaaro suggested in this answer you can use SESSION_EXPIRE_AT_BROWSER_CLOSE and set a timestamp on session at each request and add a custom Middleware to handle the inactivity.

这篇关于Django会话在浏览器关闭时或过期后到期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆