我使用的是Django Python。有没有办法设置会话永不过期?
从Django 1.4(及更高版本)开始,您还可以通过在设置文件中设置SESSION_COOKIE_AGE
来设置会话的持续时间。
SESSION_COOKIE_AGE
默认值:1209600(2周,以秒为单位)
会话Cookie的使用期限,以秒为单位。
我不知道无限会话,但如果您使用会话中间件并且使用巨大的AUTOLOGOUT时间,它就会工作。
100年听起来不错吗?
关于设置.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())