python 在 N 分钟不活动后将用户从 Django 站点中注销

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2539109/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-04 00:53:09  来源:igfitidea点击:

Logging users out of a Django site after N minutes of inactivity

pythondjangoauthentication

提问by Chip Tol

I'm working on a website that requires us to log a user out after N minutes of inactivity. Are there any best practices for this using Django?

我正在开发一个网站,该网站要求我们在 N 分钟不活动后将用户注销。使用 Django 是否有任何最佳实践?

回答by Lance McNearney

Take a look at the session middlewareand its settings. Specifically these two:

查看会话中间件及其设置。具体这两个:

SESSION_COOKIE_AGE

Default: 1209600 (2 weeks, in seconds)

The age of session cookies, in seconds.

SESSION_SAVE_EVERY_REQUEST

Default: False

Whether to save the session data on every request. If this is False (default), then the session data will only be saved if it has been modified -- that is, if any of its dictionary values have been assigned or deleted.

SESSION_COOKIE_AGE

默认值:1209600(2 周,以秒为单位)

会话 cookie 的年龄,以秒为单位。

SESSION_SAVE_EVERY_REQUEST

默认值:假

是否在每个请求上保存会话数据。如果这是 False(默认),则会话数据仅在已被修改时才会保存——也就是说,如果已分配或删除了其任何字典值。

Setting a low SESSION_COOKIE_AGEand turning SESSION_SAVE_EVERY_REQUESTon should work to create "sliding" expiration.

设置一个低点SESSION_COOKIE_AGE并打开SESSION_SAVE_EVERY_REQUEST应该可以创建“滑动”到期。

回答by MattH

Setting the session cookie age in the django session middleware just sets the expiry time in the set-cookie header passed back to the browser. It's only browser compliance with the expiry time that enforces the "log out".

在 django 会话中间件中设置会话 cookie 年龄只是在传递回浏览器的 set-cookie 标头中设置到期时间。只有浏览器遵守强制“注销”的到期时间。

Depending on your reasons for needing the idle log-out, you might not consider browser compliance with the expiry time good enough. In which case you'll need to extend the session middleware to do so.

根据您需要空闲注销的原因,您可能认为浏览器符合到期时间不够好。在这种情况下,您需要扩展会话中间件才能这样做。

For example you might store an expiry time in your session engine which you update with requests. Depending on the nature of traffic to your site, you may wish to only write back to the session object once in X seconds to avoid excessive db writes.

例如,您可以在会话引擎中存储一个到期时间,并根据请求进行更新。根据站点流量的性质,您可能希望只在 X 秒内回写一次会话对象,以避免过多的数据库写入。

回答by Steve Jalim

Try setting settings.SESSION_COOKIE_AGE to N * 60 seconds.

尝试将 settings.SESSION_COOKIE_AGE 设置为 N * 60 秒。

http://docs.djangoproject.com/en/dev/ref/settings/#session-cookie-age

http://docs.djangoproject.com/en/dev/ref/settings/#session-cookie-age