Fix Python – Python Requests and persistent sessions

Question

Asked By – ChrisGuest

I am using the requests module.
I have figured out how to submit data to a login form on a website and retrieve the session key, but I can’t see an obvious way to use this session key in subsequent requests.
Can someone fill in the ellipsis in the code below or suggest another approach?

>>> import requests
>>> login_data =  {'formPosted': '1', 'login_email': 'me@example.com', 'password': 'pw'}
>>> r = requests.post('https://localhost/login.py', login_data)
>>> 
>>> r.text
'You are being redirected <a href="profilePage?_ck=1349394964">here</a>'
>>> r.cookies
{'session_id_myapp': '127-0-0-1-825ff22a-6ed1-453b-aebc-5d3cf2987065'}
>>> 
>>> r2 = requests.get('https://localhost/profile_data.json', ...)

Now we will see solution for issue: Python Requests and persistent sessions


Answer

You can easily create a persistent session using:

s = requests.Session()

After that, continue with your requests as you would:

s.post('https://localhost/login.py', login_data)
# logged in! cookies saved for future requests.
r2 = s.get('https://localhost/profile_data.json', ...)
# cookies sent automatically!
# do whatever, s will keep your cookies intact :)

For more about Sessions: https://requests.readthedocs.io/en/latest/user/advanced/#session-objects

This question is answered By – Anuj Gupta

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0