add a cookie to requests session

Viewed 2657

I want to start a requests.Session() and add a cookie before starting the first request. I expected to have a cookie argument or something similar to do this

def session_start()
    self.session = requests.Session(cookies=['session-id', 'xxx'])

def req1():
    self.session.get('example.org')

def req2():
    self.session.get('example2.org')

but this wont work, I only can provide cookies in the .get() method. Do I need to do a "dummy request" in session_start() or is there a way to prepare the cookie before starting the actual request?

3 Answers

From the documentation:

Note, however, that method-level parameters will not be persisted across requests, even if using a session. This example will only send the cookies with the first request, but not the second:

s = requests.Session()

r = s.get('https://httpbin.org/cookies', cookies={'from-my': 'browser'})
print(r.text)
# '{"cookies": {"from-my": "browser"}}'

r = s.get('https://httpbin.org/cookies')
print(r.text)
# '{"cookies": {}}'

So session objects will persist any cookies that the url requests themselves set, but if you provide a cookie as an argument it will not persist on the next request.

You can add cookies in manually that persist too though, from the documentation: "If you want to manually add cookies to your session, use the Cookie utility functions to manipulate Session.cookies." https://requests.readthedocs.io/en/master/user/advanced/#session-objects

Where it links to on how to manipulate cookies: https://requests.readthedocs.io/en/master/api/#api-cookies

session.cookies is a RequestsCookieJar and you can add cookies to that after constructing the session:

self.session = requests.Session()
self.session.cookies.set('session-id', 'xxx')
Related