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

BSG*_*BSG 0 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)
Run Code Online (Sandbox Code Playgroud)

vij*_*ker 6

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']
Run Code Online (Sandbox Code Playgroud)

  • 我使用的是 Python 3.6,必须将导入更改为:“from http.cookies import SimpleCookie”,然后“c = SimpleCookie()” (2认同)

Mar*_*vin 5

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