如何显示django-cookie的到期时间?

时间:2012-10-10 11:13:41

标签: django cookies

在我的getCookie函数中,我想显示给定cookie的名称和到期时间,但我能够归档的所有内容都是它的名称,作为字符串。

Cookie已设置,并按预期到期,我只想以简单的方式显示剩余时间。

def setCookie(request):
    cook = HttpResponseRedirect('/getCookie/')
    cook.set_cookie('theCookie', value='Dough', max_age=15)

    return cook

def getCookie(request):
    s=""
    if request.COOKIES.has_key('theCookie'):
        s += request.COOKIES['theCookie']
        #s += request.COOKIES['theCookie'].expires..? HERE?

    else:
        s="Sorry, your cookie has expired"
    return HttpResponse(s)

4 个答案:

答案 0 :(得分:5)

request.COOKIES仅包含已解析cookie的键/值映射。但是request.META['HTTP_COOKIE']包含原始cookie字符串,可以由Python cookie.SimpleCookie类解析以获取max-age http://docs.python.org/library/cookie.html

答案 1 :(得分:2)

Cookie的过期时间可以像这样:

import Cookie
val = request.META['HTTP_COOKIE']
c = Cookie.SimpleCookie()
c.load(val)
c['cookie-name'].keys()
... 
comment,domain,secure,expires,max-age,version,path,httponly

expires = c['cookie-name']['expires']

答案 2 :(得分:-3)

简短回答:无法完成。

答案 3 :(得分:-4)

尝试get_expiry_age:

request.COOKIES['theCookie'].get_expiry_age()