Skip to content
Myr

utils.py

This file

Path

requests/utils.py

72 lines · 1.6 KiB · Python

Last changed by

add_dict_to_cookiejarKenneth Reitzbefore adoptione477fce

History of this file

Take it

1# -*- coding: utf-8 -*-23"""4requests.utils5~~~~~~~~~~~~~~67This module provides utlity functions that are used within Requests8that are also useful for external consumption.910"""1112import cookielib131415def dict_from_cookiejar(cookiejar):16    """Returns a key/value dictionary from a CookieJar."""1718    cookie_dict = {}1920    for _, cookies in cookiejar._cookies.items():21        for _, cookies in cookies.items():22            for cookie in cookies.values():23                # print cookie24                cookie_dict[cookie.name] = cookie.value2526    return cookie_dict272829def cookiejar_from_dict(cookie_dict):30    """Returns a CookieJar from a key/value dictionary."""3132    # return cookiejar if one was passed in33    if isinstance(cookie_dict, cookielib.CookieJar):34        return cookie_dict3536    # create cookiejar37    cj = cookielib.CookieJar()3839    cj = add_dict_to_cookiejar(cj, cookie_dict)4041    return cj424344def add_dict_to_cookiejar(cj, cookie_dict):45    """Returns a CookieJar from a key/value dictionary."""4647    for k, v in cookie_dict.items():4849        cookie = cookielib.Cookie(50            version=0,51            name=k,52            value=v,53            port=None,54            port_specified=False,55            domain='',56            domain_specified=False,57            domain_initial_dot=False,58            path='/',59            path_specified=True,60            secure=False,61            expires=None,62            discard=True,63            comment=None,64            comment_url=None,65            rest={'HttpOnly': None},66            rfc2109=False67        )6869        # add cookie to cookiejar70        cj.set_cookie(cookie)7172    return cj