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
Yes, there is. Use requests. Session and it will do keep-alive by default.
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.
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.
Any requests that you make within a session will automatically reuse the appropriate connection!
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"}}'
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With