Django:Cookie设置在30秒内到期实际在30分钟内到期? [英] Django: Cookie set to expire in 30 seconds is actually expiring in 30 minutes?

查看:448
本文介绍了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 
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 201 1 

我做错了什么?

解决方案

您可以使用 max_age 参数,秒数,而不是使用 expires ;将为您计算 expires 。您的 datetime.now()的问题可能是您没有使用UTC(您可以使用 datetime.utcnow() $ b

  hr.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 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.

这篇关于Django:Cookie设置在30秒内到期实际在30分钟内到期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆