如何在django中设置会话永不过期

时间:2015-03-25 07:44:50

标签: python django session timeout

我正在使用Django-Python。有没有办法设置会话永不过期?

2 个答案:

答案 0 :(得分:5)

从Django 1.4(及更高版本)开始,您还可以通过在设置文件中设置SESSION_COOKIE_AGE来设置会话的持续时间。

SESSION_COOKIE_AGE
Default: 1209600 (2 weeks, in seconds)
The age of session cookies, in seconds.

答案 1 :(得分:2)

我不知道无限会话,但如果您使用会话中间件 并且使用巨大的AUTOLOGOUT时间,它将起作用。

100年听起来不错吗?

在settings.py

# time in minutes
# 60min*24hours*365days*100years
AUTO_LOGOUT = 52560000

创建中间件并将其添加到中间件部分的settings.py

from datetime import datetime, timedelta
from django.conf import settings
from django.contrib import auth
from django.utils.translation import ugettext as _

class AutoLogout:

    def process_request(self, request):

        if not request.user.is_authenticated():
            # Can't log out if is not logged in
            return
        try:
            # last click
            last_touch = datetime.strptime(request.session['last_touch'], "%Y-%m-%d %H:%M:%S.%f")
            # getting auto logout time
            auto_logout_time = settings.AUTO_LOGOUT

            try:
                if datetime.now() - last_touch > timedelta(0, auto_logout_time * 60, 0):
                    del request.session['last_touch']
                    auth.logout(request)
                    request.session['warning'] = unicode(_("You have been logged out"))
                    return
            except Exception as e:
                # It should not reach this point
                auth.logout(request)
                del request.session['last_touch']
                request.session['warning'] = unicode(_("You have been logged out"))

        except KeyError:
            pass

         request.session['last_touch'] = str(datetime.now())