由于Django中的不活动,如何到期会话? [英] How to expire session due to inactivity in Django?

查看:172
本文介绍了由于Django中的不活动,如何到期会话?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们的Django应用程序具有以下会话管理需求。

Our Django application has the following session management requirements.


  1. 用户关闭浏览器时会话到期。
  2. $ b
  3. >在不活动期结束前几分钟,警告即将到期的用户将到期。

  4. 如果用户在应用程序中进行的长时间的业务活动不涉及发送到服务器的请求,那么,会话不能超时。

  1. Sessions expire when the user closes the browser.
  2. Sessions expire after a period of inactivity.
  3. Detect when a session expires due to inactivity and display appropriate message to the user.
  4. Warn users of a impending session expiry a few minutes before the end of the inactivity period. Along with the warning, provide users an option to extend their session.
  5. If user is working on a long business activity within the app that doesn't involve requests being sent to the server, the session must not timeout.

阅读文档,Django代码和一些与此相关的博客文章后,我想出了以下

After reading the documentation, Django code and some blog posts related to this, I have come up with the following implementation approach.

需求1

此要求很容易通过将SESSION_EXPIRE_AT_BROWSER_CLOSE设置为True来实现。

Requirement 1
This requirement is easily implemented by setting SESSION_EXPIRE_AT_BROWSER_CLOSE to True.

需求2

我看到了一些建议,希望使用SESSION_COOKIE_AGE设置会话有效期。但是此方法有以下问题。

Requirement 2
I have seen a few recommendations to use SESSION_COOKIE_AGE to set the session expiry period. But this method has the following problems.


  • 会话总是在SESSION_COOKIE_AGE结束时到期,即使用户正在使用应用程序。 (可以通过使用自定义中间件将每个请求的会话到期设置为SESSION_COOKIE_AGE,或者通过将每个请求的会话设置为SESSION_SAVE_EVERY_REQUEST为true,来防止此问题,但由于使用SESSION_COOKIE_AGE,下一个问题是不可避免的)。

  • The session always expires at the end of the SESSION_COOKIE_AGE even if the user is actively using the application. (This can be prevented by setting the session expiry to SESSION_COOKIE_AGE on every request using a custom middleware or by saving the session on every request by setting SESSION_SAVE_EVERY_REQUEST to true. But the next problem is unavoidable due to the use of SESSION_COOKIE_AGE.)

由于Cookie的工作方式,SESSION_EXPIRE_AT_BROWSER_CLOSE和SESSION_COOKIE_AGE是互斥的,即Cookie会在浏览器关闭或指定的到期时间到期。如果使用SESSION_COOKIE_AGE并且用户在Cookie过期之前关闭浏览器,则Cookie将被保留,并且重新打开浏览器将允许用户(或任何其他人)进入系统,而无需重新身份验证。

Due to the way cookies work, SESSION_EXPIRE_AT_BROWSER_CLOSE and SESSION_COOKIE_AGE are mutually exclusive i.e. the cookie either expires on browser close or at the specified expiry time. If SESSION_COOKIE_AGE is used and the user closes the browser before the cookie expires, the cookie is retained and reopening the browser will allow the user (or anyone else) into the system without being re-authenticated.

Django仅依赖于存在的cookie来确定会话是否处于活动状态。它不会检查会话存储的会话过期日期。

Django relies only on the cookie being present to determine if the session is active. It doesn't check the session expiry date stored with the session.

可以使用以下方法


  • 不设置SESSION_COOKIE_AGE。

  • 设置过期日期

  • 在SessionMiddleware中覆盖process_request并检查会话是否过期。

需求3

当我们检测到(在上面的自定义SessionMiddleware中),在请求上设置一个属性来指示会话到期。此属性可用于向用户显示适当的消息。

Requirement 3
When we detect that the session has expired (in the custom SessionMiddleware above), set an attribute on the request to indicate session expiry. This attribute can be used to display an appropriate message to the user.

需求4

使用JavaScript检测用户不活动,提供警告以及扩展会话的选项。如果用户希望延长,请向服务器发送保持活动脉冲以延长会话。

Requirement 4
Use JavaScript to detect user inactivity, provide the warning and also an option to extend the session. If the user wishes to extend, send a keep alive pulse to the server to extend the session.

需求5

使用JavaScript来检测用户活动(在长期业务操作期间),并向服务器发送保持活动脉冲以防止会话过期。

Requirement 5
Use JavaScript to detect user activity (during the long business operation) and send keep alive pulses to the server to prevent session from expiring.

上面的实现方法看起来很复杂,我想知道是否有更简单的方法(特别是对于需求2)。

The above implementation approach seem very elaborate and I was wondering if there might a simpler method (especially for Requirement 2).

任何见解都将非常感激。

Any insights will be highly appreciated.

推荐答案

...使用 SESSION_EXPIRE_AT_BROWSER_CLOSE 设置在浏览器关闭会话。

Here's an idea... Expire the session on browser close with the SESSION_EXPIRE_AT_BROWSER_CLOSE setting. Then set a timestamp in the session on every request like so.

request.session['last_activity'] = datetime.now()

并添加中间件以检测会话是否过期。这样的东西应该处理整个过程...

and add a middleware to detect if the session is expired. something like this should handle the whole process...

from datetime import datetime
from django.http import HttpResponseRedirect

class SessionExpiredMiddleware:
    def process_request(request):
        last_activity = request.session['last_activity']
        now = datetime.now()

        if (now - last_activity).minutes > 10:
            # Do logout / expire session
            # and then...
            return HttpResponseRedirect("LOGIN_PAGE_URL")

        if not request.is_ajax():
            # don't set this for ajax requests or else your
            # expired session checks will keep the session from
            # expiring :)
            request.session['last_activity'] = now

然后你只需要创建一些url和视图来返回相关数据

Then you just have to make some urls and views to return relevant data to the ajax calls regarding the session expiry.

当用户选择续订会话时,可以说,所有你需要做的是设置 requeset.session [ last_activity'] 到当前时间

when the user opts to "renew" the session, so to speak, all you have to do is set requeset.session['last_activity'] to the current time again

显然这个代码只是一个开始...但它应该让你在正确的路径

Obviously this code is only a start... but it should get you on the right path

这篇关于由于Django中的不活动,如何到期会话?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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