kefeizhou
kefeizhou

Reputation: 6552

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 with a http request.

I tried this but it looks like SimpleCookie class is not compatible with CookieJar (is there another Cookie class?)

import Cookie
c = Cookie.SimpleCookie()
c["name"]="value"
c['name']['expires'] = 0
c['name']['path'] = "/"
c['name']['domain'] = "mydomain.com"
cj = cookielib.CookieJar()
cj.set_cookie(cookie)

Traceback (most recent call last):
    cj.set_cookie(cookie)
  File "/usr/lib/python2.6/cookielib.py", line 1627, in set_cookie
    if cookie.domain not in c: c[cookie.domain] = {}
AttributeError: 'SimpleCookie' object has no attribute 'domain'

Upvotes: 15

Views: 22703

Answers (2)

Michael
Michael

Reputation: 7736

Looking at cookielib, you get:

try:
    from cookielib import Cookie, CookieJar         # Python 2
except 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.

Upvotes: 11

UlFie
UlFie

Reputation: 97

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).

Upvotes: 2

Related Questions