I am making HTTP requests using the requests library in python, but I need the ip address from the server that responded the http request and I'm trying to avoid to make two calls (and possibly having a different ip address from the one that responded the request.
Is that possible? Does any python http library allows me to do that?
ps: I also need to make HTTPS requests and to use an authenticated proxy.
Update 1:
Example:
import requests
proxies = {
"http": "http://user:password@10.10.1.10:3128",
"https": "http://user:password@10.10.1.10:1080",
}
response = requests.get("http://example.org", proxies=proxies)
response.ip # This doesn't exist, this is just an what I would like to do
then, I would like to know to which IP address requests connected from a method or property in the response. In other libraries I was able to do that by finding the sock object and using the getpeername() method.
It turns out that it's rather involved.
Here's a monkey-patch while using
requests
version 1.2.3:Wrapping the
_make_request
method onHTTPConnectionPool
to store the response fromsocket.getpeername()
on theHTTPResponse
instance.For me on python 2.7.3, this instance was available on
response.raw._original_response
.Yields:
Ah, if there's a proxy involved or the response is chunked, the
HTTPConnectionPool._make_request
isn't called.So here's a new version patching
httplib.getresponse
instead:Running:
Also checked running with proxies set; proxy address is returned.
Update 2016/01/19
est offers an alternative that doesn't need the monkey-patch:
Update 2016/05/19
From the comments, copying here for visibility, Richard Kenneth Niescior offers the following that is confirmed working with requests 2.10.0 and Python 3.