Search code examples
pythoncookiespython-requestshttprequest

Putting a `Cookie` in a `CookieJar`


I'm using the Python Requests library to make HTTP requests. I obtain a cookie from the server as text. How do I turn that into a CookieJar with the cookie in it?


Solution

  • 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