Skip to content Skip to sidebar Skip to footer

Python - Add Cookie To Cookiejar

How do I create a cookie and add it to a CookieJar instance in python? I have all the info for the cookie (name, value, domain, path, etc) and I don't want to extract a new cookie

Solution 1:

Looking at cookielib, you get:

try:
    from cookielib import Cookie, CookieJar         # Python 2except ImportError:
    from http.cookiejar import Cookie, CookieJar    # Python 3
cj = CookieJar()
# Cookie(version, name, value, port, port_specified, domain, # domain_specified, domain_initial_dot, path, path_specified, # secure, discard, comment, comment_url, rest)
c = Cookie(None, 'asdf', None, '80', '80', 'www.foo.bar', 
       None, None, '/', None, False, False, 'TestCookie', None, None, None)
cj.set_cookie(c)
print cj

Gives:

<cookielib.CookieJar[<Cookie asdf for www.foo.bar:80/>]>

There are no real sanity checks for the instantiation parameters. The ports have to be strings, not int.

Solution 2:

The crucial point here is that method cj.set_cookie expects an object of class cookielib.Cookie as its parameter (so yes, there is another Cookie class), not an object of class Cookie.SimpleCookie (or any other class found in module Cookie). These classes are (as observed) simply not compatible, despite the confusing similarity of names.

Note that the parameter list of the constructor for cookielib.Cookie might have changed at some point in the past (and might change again in the future as this class does not seem to be expected to be used outside of cookielib), at least help(cookielib.Cookie) currently gives me

# Cookie(version, name, value, port, port_specified, domain,# domain_specified, domain_initial_dot, path, path_specified,# secure, expires, discard, comment, comment_url, rest, rfc2109=False)

Note the additional expires parameter and the parameter rfc2109 used but not documented in the code in @Michael's answer above, so the example should become something like

c = Cookie(None, 'asdf', None, '80', True, 'www.foo.bar', 
   True, False, '/', True, False, '1370002304', False, 'TestCookie', None, None, False)

(also replacing some Boolean constants for None where applicable).

Post a Comment for "Python - Add Cookie To Cookiejar"