pythonhttprequestpython-requestscookiejar

requests.Session() load cookies from CookieJar


How can I load a CookieJar to a new requests.Session object?

cj = cookielib.MozillaCookieJar("mycookies.txt")
s = requests.Session()

This is what I create, now the session will store cookies, but I want it to have my cookies from the file
(The session should load the cookieJar). How can this be achieved?
I searched the documentation but I can only find code examples and they are never loading a cookieJar, just saving cookies during one session.


Solution

  • There's an optional cookies= that can be provided for a requests.Session (as well as request) objects:

    cookies = None

    A CookieJar containing all currently outstanding cookies set on this session. By default it is a RequestsCookieJar, but may be any other cookielib.CookieJar compatible object.

    see: https://2.python-requests.org/en/latest/api/#requests.Session.cookies

    So it becomes:

    s = requests.Session(cookies=cj)
    

    Update: I was confusing the the requests.get, request.post etc..., as correctly pointed out by mata in comments - cookies is an attribute of the session object, not a init parameter, so this won't work. s.cookies = cj after constructing the session will:

    Therefore, use:

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