Django:设置为30秒过期的Cookie实际上在30分钟后过期?
这是我的代码:
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
这是日志输出:
set_terminal_cookie
2011-04-05 23:16:36.706624
2011-04-05 23:17:06.706806
但是,如果我在Firefox浏览器中查看'user_id'这个cookie,'Expires'日期是:
Tue Apr 5 23:50:07 2011
我哪里做错了?
4 个回答
0
可以试试这个:
hr.set_cookie('user_id', user_id, max_age=30)
max_age 参数是你希望这个 cookie 保持有效的时间,单位是秒。
1
对于那些在使用签名 cookie 时遇到同样问题的人,你需要使用 get_signed_cookie()
方法,并且要加上 max_age
属性。我尝试用 set_signed_cookie()
方法来设置它,但在再次获取时并没有效果。
所以,这样设置不会让你的 cookie 过期:
cookie_max_age = settings.TWO_FACTOR_REMEMBER_USER_SECONDS
response.set_signed_cookie('key', max_age=cookie_max_age)
但是像下面这样获取时,它应该能正常工作(无论是否在 cookie 上设置 max_age
):
cookie_max_age = 3600
cookie = request.get_signed_cookie('key', max_age=cookie_max_age)
13
你可以用 max_age
参数来设置一个秒数,而不是使用 expires
;这样系统会自动帮你计算 expires
的值。你在使用 datetime.now()
时可能遇到的问题是你没有使用 UTC 时间(你可以用 datetime.utcnow()
来代替)。
hr.set_cookie('user_id', user_id, max_age=30)
这个故事的教训是:看看文档;文档里解释了你需要使用 UTC 的 datetime
对象,并且介绍了 max_age
的用法。