3
我正在使用Django-Python。有沒有辦法設置會話永不過期?我如何設置會話永遠不會在django中過期
我正在使用Django-Python。有沒有辦法設置會話永不過期?我如何設置會話永遠不會在django中過期
我不知道無限的會話,但如果您使用會話中間件 並使用巨大的AUTOLOGOUT時間,它將工作。
100年的聲音好嗎?在settings.py
# time in minutes
# 60min*24hours*365days*100years
AUTO_LOGOUT = 52560000
創建一箇中間件,並將其添加在中間件部分
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(或更高版本)到settings.py中,你還可以設置通過在設置文件中設置SESSION_COOKIE_AGE來實現會話持續時間。
SESSION_COOKIE_AGE
Default: 1209600 (2 weeks, in seconds)
The age of session cookies, in seconds.
我將使用默認超時2周。不管怎麼說,還是要謝謝你。 – user2307087 2015-03-26 00:21:56