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

How can I set session never expire in django

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

我不知道无限会话,但如果你使用你的会话中间件 并使用大量的 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())

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

SESSION_COOKIE_AGE

Default: 1209600 (2 weeks, in seconds)

The age of session cookies, in seconds.