Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

add a cookie to requests session

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?

like image 878
Asara Avatar asked Oct 23 '25 13:10

Asara


1 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": {}}'
like image 140
Steffen Andersland Avatar answered Oct 26 '25 03:10

Steffen Andersland



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!