【问题标题】:Python - convert set-cookies response to dict of cookiesPython - 将 set-cookies 响应转换为 cookie 的字典
【发布时间】:2014-02-03 08:23:53
【问题描述】:

如何将response['set-cookie'] 输出字符串从httplib2 响应转换为like

"cookie1=xxxyyyzzz;Path=/;Expires=Wed, 03-Feb-2015 08:03:12 GMT;Secure;HttpOnly, cookie2=abcdef;Path=/;Secure"

{'cookie1':'xxxyyyzzz','cookies2':'abcdef'}

【问题讨论】:

  • 你试过什么?似乎是在分隔符上拆分字符串的简单案例,此外the set-cookie header syntax 不允许在 cookie 名称 值中使用分隔符,因此您甚至不需要解析引用结构。跨度>
  • 如果你使用请求,你可以只使用response.cookies 并取回字典。

标签: python cookies python-3.3


【解决方案1】:

使用http.cookies:

>>> c = "cookie1=xxxyyyzzz;Path=/;Expires=Wed, 03-Feb-2015 08:03:12 GMT;Secure;HttpOnly, cookie2=abcdef;Path=/;Secure"
>>> from http.cookies import SimpleCookie
>>> cookie = SimpleCookie()
>>> cookie.load(c)
>>> cookie
<SimpleCookie: cookie1='xxxyyyzzz' cookie2='abcdef'>
>>> {key: value.value  for key, value in cookie.items()}
{'cookie1': 'xxxyyyzzz', 'cookie2': 'abcdef'}

【讨论】:

  • 优秀。这确实应该是 BaseCookie 类上的方法 as_dict
【解决方案2】:
def parse_dict_cookies(cookies):
    result = {}
    for item in cookies.split(';'):
        item = item.strip()
        if not item:
            continue
        if '=' not in item:
            result[item] = None
            continue
        name, value = item.split('=', 1)
        result[name] = value
    return result

【讨论】:

    【解决方案3】:

    如果您使用的是requestsresponse.cookies 是类字典对象

    【讨论】:

    • 确实是dict*like,但不代表response['set-cookie']。
    猜你喜欢
    • 1970-01-01
    • 2021-06-10
    • 2022-11-30
    • 2013-02-19
    • 2016-10-16
    • 1970-01-01
    • 2022-11-03
    • 1970-01-01
    • 2017-07-21
    相关资源
    最近更新 更多