【问题标题】:python - get cookie expiry time using the requests librarypython - 使用请求库获取 cookie 过期时间
【发布时间】:2014-04-29 21:47:16
【问题描述】:

我正在尝试获取从服务器检索到的特定 cookie 的到期时间:

s = requests.session()
r = s.get("http://localhost/test")
r.cookies

这将列出服务器发送的所有 cookie(我得到 2 个 cookie):

<<class 'requests.cookies.RequestsCookieJar'>[<Cookie PHPSESSID=cusa6hbtb85li8po
argcgev221 for localhost.local/>, <Cookie WebSecu=f for localhost.local/test>]>

当我这样做时:

r.cookies.keys

我明白了:

<bound method RequestsCookieJar.items of <<class 'requests.cookies.RequestsCooki
eJar'>[Cookie(version=0, name='PHPSESSID', value='30tg9vn9376kmh60ana2essfi3', p
ort=None, port_specified=False, domain='localhost.local', domain_specified=False
, domain_initial_dot=False, path='/', path_specified=True, secure=False, expires
=None, discard=True, comment=None, comment_url=None, rest={}, rfc2109=False), Co
okie(version=0, name='WebSecu', value='f', port=None, port_specified=False, doma
in='localhost.local', domain_specified=False, domain_initial_dot=False, path='/test', path_specified=False, secure=False, expires=1395491371, discard=Fals
e, comment=None, comment_url=None, rest={}, rfc2109=False)]>>

如您所见,我们有两个 cookie。我想获取名为“WebSecu”的 cookie 的到期时间

谢谢

【问题讨论】:

    标签: python cookies python-requests


    【解决方案1】:

    requests 中,cookie jar 是一个非常特殊的对象。如果您这样做,您可能会注意到:

    r.cookies['WebSecu']
    

    您将收到该 cookie 的值作为字符串(在您的示例中为 f)。要获取保存该信息的实际 cookie 对象,您必须像这样遍历 cookie jar:

    expires = None
    for cookie in r.cookies:
        if cookie.name == 'WebSecu':
            expires = cookie.expires
    

    【讨论】:

    • 一种更“Pythonic”的方式:expires = next(x for x in r.cookies if x.name == 'WebSecu').expires
    • 'Pythonic' 是一个被人们试图听起来更优越的词。如果“Pythonic”意味着任何有价值的东西,那就意味着“易于理解”。如果你要给某人你的单线和上面的 for 循环,大多数人将不得不花费额外的时间来理解单线。 (尤其是大多数试图从这个网站学习的人。)
    • 我已经关注了这个方法,虽然我的 SESSION_COOKIE_AGE 是 3600 我得到 1510315939,这不是毫秒,这是什么?似乎与我的 SESSION_COOKIE_AGE 无关。
    • 老东西,但想指出答案中的解决方案与上述“pythonic”方式之间存在很大差异。想象多个同名的 cookie,answer 的解决方案会选择最后一个 cookie,而 onlineer 会选择迭代中的第一个。它们不一样。
    • @DidinaDeen 这是作为时间戳的到期日期。执行from datetime import datetime; print(datetime.fromtimestamp(expires)) 将其视为人类可读的日期和时间。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-11
    • 2011-09-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多