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 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With