本文介绍了Django:Cookie设置在30秒内到期实际在30分钟内到期?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是我的代码:
def update_session(request):
如果没有request.is_ajax()或not request.method =='POST':
return HttpResponseNotAllowed(['POST'])
user_id = request.POST.get('u')
hr = set_terminal_cookie(user_id)
return hr
def set_terminal_cookie(user_id):
print'set_terminal_cookie'
hr = HttpResponse('ok')
print datetime.datetime.now( )
expiry_time = datetime.datetime.now()+ datetime.timedelta(seconds = 30)
打印expiry_time
hr.set_cookie('user_id',user_id,expiry_time)
返回hr
这是日志输出:
set_terminal_cookie
但是,如果我在Firefox中检查'user_id'cookie,'Expires'日期是:
2011-04-05 23:16:36.706624
2011-04-05 23:17:06.706806
Tue Apr 5 23:50:07 201 1
我做错了什么?
解决方案您可以使用
max_age
参数,秒数,而不是使用expires
;将为您计算expires
。您的datetime.now()
的问题可能是您没有使用UTC(您可以使用datetime.utcnow()
$ bhr.set_cookie('user_id',user_id,max_age = 30)
道德的故事:;它解释了您需要使用UTC
datetime
对象并描述max_age
。This is my code:
def update_session(request): if not request.is_ajax() or not request.method=='POST': return HttpResponseNotAllowed(['POST']) user_id = request.POST.get('u') hr = set_terminal_cookie(user_id) return hr def set_terminal_cookie(user_id): print 'set_terminal_cookie' hr = HttpResponse('ok') print datetime.datetime.now() expiry_time = datetime.datetime.now() + datetime.timedelta(seconds=30) print expiry_time hr.set_cookie('user_id', user_id, expiry_time) return hr
This is the log output:
set_terminal_cookie 2011-04-05 23:16:36.706624 2011-04-05 23:17:06.706806
However, if I then check the 'user_id' cookie in Firefox, the 'Expires' date is:
Tue Apr 5 23:50:07 2011
What am I doing wrong?
解决方案You can use the
max_age
parameter with a number of seconds instead of usingexpires
; it'll calculateexpires
for you. The problem with yourdatetime.now()
may be that you're not using UTC (you can usedatetime.utcnow()
instead).hr.set_cookie('user_id', user_id, max_age=30)
Moral of the story: read the documentation; it explains both that you need to use a UTC
datetime
object and describesmax_age
.这篇关于Django:Cookie设置在30秒内到期实际在30分钟内到期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!