Putting a `Cookie` in a `CookieJar`

Old versions of the Requests library (0.14.2 and older) put new cookies in the jar for you when you pass a CookieJar object:

import requests
import cookielib

URL = '...whatever...'
jar = cookielib.CookieJar()
r = requests.get(URL, cookies=jar)
r = requests.get(URL, cookies=jar)

The first request to the URL fills the jar and the second request sends the cookies back to the server.

This doesn't work starting with Requests 1.0.0, released in 2012.


A Requests Session will receive and send cookies.

s = requests.Session()

s.get('http://httpbin.org/cookies/set/sessioncookie/123456789')
r = s.get("http://httpbin.org/cookies")

print(r.text)
# '{"cookies": {"sessioncookie": "123456789"}}'

(The code above is stolen from Session Objects.)

If you want cookies to persist on disk between runs of your code, you can directly use a CookieJar and save/load them:

from http.cookiejar import LWPCookieJar
import requests

cookie_file = '/tmp/cookies'
jar = LWPCookieJar(cookie_file)

# Load existing cookies (file might not yet exist)
try:
    jar.load()
except:
    pass

s = requests.Session()
s.cookies = jar

s.get('http://httpbin.org/cookies/set/sessioncookie/123456789')
r = s.get("http://httpbin.org/cookies")

# Save cookies to disk, even session cookies
jar.save(ignore_discard=True)

Then look in the file /tmp/cookies:

#LWP-Cookies-2.0
Set-Cookie3: sessioncookie=123456789; path="/"; domain="httpbin.org"; path_spec; discard; version=0