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'
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.
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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With