Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Requests and persistent sessions

I am using the requests module (version 0.10.0 with Python 2.5). 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':'[email protected]', 'password':'pw'} >>> r = requests.post('https://localhost/login.py', login_data) >>>  >>> r.text u'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', ...) 
like image 245
ChrisGuest Avatar asked Oct 05 '12 00:10

ChrisGuest


People also ask

What is Python requests Session?

Usind Session object with Python Requests. The Requests Session object allows you to persist specific parameters across requests to the same site. To get the Session object in Python Requests, you need to call the requests. Session() method. The Session object can store such parameters as cookies and HTTP headers.

Does request use certifi?

Requests verifies SSL certificates for HTTPS requests, just like a web browser.

Is requests get synchronous Python?

Yes, requests. get is a synchronous operation. It waits for the page contents to be pulled into python as str. The time difference you see is indeed due to the execution of javascipt and the fetching of additional files in the browser.


1 Answers

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.kennethreitz.org/en/master/user/advanced/#session-objects

like image 131
Anuj Gupta Avatar answered Oct 18 '22 15:10

Anuj Gupta