Add a cookie to the http.cookiejar

posted on 2013-02-15

When looking for a method to add a cookie to an http.cookiejar in Python 3, all of the posts I could find created their own Cookie instance. However, the Cookie documentation states that it should not be necessary. I quote:

This class represents Netscape, RFC 2109 and RFC 2965 cookies. It is not expected
that users of http.cookiejar construct their own Cookie instances. Instead, if necessary,
call make_cookies() on a CookieJar instance.

The make_cookies() documentation points to extract_cookies().

Because I already had a request and a response object ready, I decided to use extract_cookies after adding the extra Cookies to the response headers, like so:

#!/usr/bin/python3
import urllib.request
import urllib.parse
import http.cookiejar

if __name__ == "__main__":
    cj = http.cookiejar.CookieJar()
    opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj))
    request = urllib.request.Request('http://bneijt.nl/')
    response = opener.open(request)
    print("Before")
    print(cj._cookies) #Only for debugging

    #Add my own cookie responses here
    response.headers.add_header('Set-Cookie',
        'Life=ok; expires=Sat, 17-Aug-2013 06:49:03 GMT; path=/; domain=.bneijt.nl; HttpOnly')
    cj.extract_cookies(response, request)
    print("After")
    print(cj._cookies)

Not the most beautiful solution, but at least I don't have to make my own Cookie instance. Here is the source.