3

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?

Asara
  • 2,791
  • 3
  • 26
  • 55
  • Does this answer your question? [How to use cookies in Python Requests](https://stackoverflow.com/questions/31554771/how-to-use-cookies-in-python-requests) – revliscano Jul 02 '20 at 13:14
  • no not really, I have a session ID from a login that I want to use again, but I want to set it when I create the session with requests.Session(), not only when I do the first request – Asara Jul 03 '20 at 07:23

3 Answers3

5

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": {}}'
  • 1
    ok thats not really an answer to my problem :) and anyway, this shouldn't be a problem, because my response will again return the session cookie – Asara Jul 03 '20 at 07:21
2

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')
Sjoerd
  • 74,049
  • 16
  • 131
  • 175
0

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

Elixir
  • 31
  • 2