Django: Cookie set to expire in 30 seconds is actually expiring in 30 minutes?
Solution 1
You can use the max_age
parameter with a number of seconds instead of using expires
; it'll calculate expires
for you. The problem with your datetime.now()
may be that you're not using UTC (you can use datetime.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 describes max_age
.
Solution 2
For those that are running in to the same problem with signed cookies, you have to use get_signed_cookie()
with the max_age
attribute. I tried setting it with the set_signed_cookie()
method, but that doesn't work when fetching it again.
So this won't expire your cookie:
cookie_max_age = settings.TWO_FACTOR_REMEMBER_USER_SECONDS
response.set_signed_cookie('key', max_age=cookie_max_age)
But when fetching it like the following, it should work (with and without setting a max_age
on the cookie):
cookie_max_age = 3600
cookie = request.get_signed_cookie('key', max_age=cookie_max_age)
simon
Updated on June 04, 2022Comments
-
simon about 2 years
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?