Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Keeping a session in python while making HTTP requests

I need to write a python script that makes multiple HTTP requests to the same site. Unless I'm wrong (and I may very well be) urllib reauthenticates for every request. For reasons I won't go into I need to be able to authenticate once and then use that session for the rest of my requests.

I'm using python 2.3.4

like image 465
Hector Scout Avatar asked May 28 '09 21:05

Hector Scout


People also ask

How do you keep a session alive in Python?

Yes, there is. Use requests. Session and it will do keep-alive by default.

How do you request a session in Python?

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.

What is session in requests?

Session object allows one to persist certain parameters across requests. It also persists cookies across all requests made from the Session instance and will use urllib3's connection pooling.

Does Python requests reuse connection?

Any requests that you make within a session will automatically reuse the appropriate connection!


2 Answers

Use Requests library. From http://docs.python-requests.org/en/latest/user/advanced/#session-objects :

The Session object allows you to persist certain parameters across requests. It also persists cookies across all requests made from the Session instance.

s = requests.session()  s.get('http://httpbin.org/cookies/set/sessioncookie/123456789') r = s.get("http://httpbin.org/cookies")  print r.text # '{"cookies": {"sessioncookie": "123456789"}}' 
like image 149
Piotr Dobrogost Avatar answered Oct 03 '22 11:10

Piotr Dobrogost


If you want to keep the authentication you need to reuse the cookie. I'm not sure if urllib2 is available in python 2.3.4 but here is an example on how to do it:

req1 = urllib2.Request(url1) response = urllib2.urlopen(req1) cookie = response.headers.get('Set-Cookie')  # Use the cookie is subsequent requests req2 = urllib2.Request(url2) req2.add_header('cookie', cookie) response = urllib2.urlopen(req2) 
like image 37
Nadia Alramli Avatar answered Oct 03 '22 12:10

Nadia Alramli