python - Django:Cookie 设置为 30 秒后过期实际上是 30 分钟后过期?

标签 python django cookies

这是我的代码:

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,则“过期”日期为:

Tue Apr 5 23:50:07 2011

我做错了什么?

最佳答案

您可以将 max_age 参数与秒数一起使用,而不是使用 expires;它会为你计算expiresdatetime.now() 的问题可能是您没有使用 UTC(您可以改用 datetime.utcnow())。

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

故事的寓意:read the documentation ;它解释了您需要使用 UTC datetime 对象并描述了 max_age

关于python - Django:Cookie 设置为 30 秒后过期实际上是 30 分钟后过期?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5559271/

相关文章:

javascript - 可调整大小的 jQuery 函数会记住 cookie 的宽度,但适用于所有单元格

ios - 清除 iOS 8.4 上 WKWebView 的 Cookie

python - (Python) 从文件创建二维列表( map )

python - 我的神经网络实现有什么问题?

python - Django 与 Postgresql 全文搜索日期和时间输入类型错误

python - 资源暂时不可用 : mod_wsgi (pid=28433): Unable to connect to WSGI daemon process

javascript - 将 javascript 字符串设置为从 Django 变量传播的值时如何转义引号?

javascript - 如何使用COOKIES jquery仅加载一次DIV

python - 如何在 Python Pandas 中使用循环更改数据帧?

python - 将两个 boolean 列转换为 Pandas 中的类 ID