我目前有一个使用 cookie 会话的 django 站点。我注意到会话被随机注销。在调试时,我发现这是由于我的代码中的逻辑查看了会话的年龄。但是,我随后注意到,在没有问题的期间,Apache 时间戳中显示了正确的时间。但是随后 tiemstamp 退回了 5 个小时,导致我的 Django 程序认为会话已过期并将其注销。
下面给大家举个例子,
[Wed Jul 31 16:12:45 2013] [error] DEBUG ok elapsed time 7
[Wed Jul 31 16:12:45 2013] [error] DEBUG ok elapsed time 1
[Wed Jul 31 10:12:46 2013] [error] DEBUG : request.user.is_authenticated()
[Wed Jul 31 10:12:46 2013] [error] DEBUG ok elapsed time 64809
[Wed Jul 31 10:12:46 2013] [error] DEBUG since begin . elapsedTime.seconds 64809
[Wed Jul 31 10:12:46 2013] [error] DEBUG request.session\\['deginRequest'\\]
[Wed Jul 31 10:12:46 2013] [error] DEBUG ok elapsed time 64801
[Wed Jul 31 10:12:46 2013] [error] DEBUG since last req . elapsedTime.seconds 64801
[Wed Jul 31 10:12:46 2013] [error] DEBUG request.session\\['lastRequest'\\]
[Wed Jul 31 10:12:47 2013] [error] DEBUG : shouldLogout
这个问题也随机发生。有任何想法吗 ?
这也是我使用的中间件(生成这些日志),
class timeOutMiddleware(object):
def process_request(self, request):
shouldLogout = False
if request.user.is_authenticated():
print "DEBUG :request.user.is_authenticated()"
if 'beginSession' in request.session:
elapsedTime = datetime.datetime.now() - \
request.session['beginSession']
print "DEBUG ok elapsed time",elapsedTime.seconds
if elapsedTime.seconds > 12*3600:
print "DEBUG since begin . elapsedTime.seconds",elapsedTime.seconds
del request.session['beginSession']
print "DEBUG request.session\[\'deginRequest\'\]"
shouldLogout = True
else:
request.session['beginSession'] = datetime.datetime.now()
if 'lastRequest' in request.session:
elapsedTime = datetime.datetime.now() - \
request.session['lastRequest']
print "DEBUG ok elapsed time",elapsedTime.seconds
if elapsedTime.seconds > 2*3600:
print "DEBUG since last req . elapsedTime.seconds",elapsedTime.seconds
del request.session['lastRequest']
shouldLogout = True
request.session['lastRequest'] = datetime.datetime.now()
username = request.user
if ####.objects.get(username=username).token:
print "DEBUG : ####.objects.get(username=username).token"
try:
token = ####.objects.get(username=username).token
url = 'https://############/%s' % (token)
response = requests.get(url)
answer = json.loads(response.text)
#print "DEBUG answer",answer
if not answer["valid"]:
shouldLogout = True
print "DEBUG",datetime.now(),"not answer[\"valid\"]"
except:
shouldLogout = True
print "DEBUG except"
else:
shouldLogout = True
print "DEBUG else"
if shouldLogout:
print "DEBUG : ",datetime.datetime.now(),"shouldLogout"
logout(request)
else:
if 'beginSession' in request.session:
del request.session['beginSession']
if 'lastRequest' in request.session:
del request.session['lastRequest']
return None