Django: Cookie set to expire in 30 seconds is actually expiring in 30 minutes?

Question:

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?

Asked By: simon

||

Answers:

Try instead:

hr.set_cookie('user_id', user_id, max_age=30)

The max_age parameter is the number of seconds that you want the cookie to last.

Answered By: Spike

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.

Answered By: Nicholas Riley

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)
Answered By: Bono
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.