Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - convert set-cookies response to dict of cookies

How to convert the response['set-cookie'] output string from httplib2 response like

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

to

{'cookie1':'xxxyyyzzz','cookies2':'abcdef'}
like image 715
Ahmed Daif Avatar asked Feb 03 '14 08:02

Ahmed Daif


2 Answers

Use 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'}
like image 194
falsetru Avatar answered Nov 03 '22 01:11

falsetru


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
like image 33
wcc526 Avatar answered Nov 03 '22 00:11

wcc526