Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python - add cookie to cookiejar

Tags:

python

cookies

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'
like image 706
kefeizhou Avatar asked Jan 13 '11 21:01

kefeizhou


People also ask

How do you create a cookie in Python?

Create cookieUse the make_response() function to get the response object from the return value of the view function. After that, the cookie is stored using the set_cookie() function of the response object. It is easy to read back cookies. The get() method of the request.

What is Cookie Jar Web?

Cookiejar is a Go interface of a simple cookie manager (to manage cookies from HTTP request and response headers) and an implementation of that interface.


1 Answers

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

like image 199
UlFie Avatar answered Sep 21 '22 05:09

UlFie