Pro Girl
Pro Girl

Reputation: 962

How to make sure request fails if proxy not working or wrong with python?

I'm trying to make sure that requests stops if the proxy does not work correctly or wrongly inserted.

In order to do so I'm willingly inserting the wrong details in the proxy dictionary, however request keeps going by discarding the non working proxy and falling back on my original Ip??? I was expecting an error of some sort.

How can I make sure that request would stop working if proxy is not working or wrong?

Here is my code:

import requests
prox_wrong = {'http':'170.83.235.162:8000'}# Wrong proxy, Wrong Type, Wrong way of setting the dictionary
url = 'http://icanhazip.com'
headers = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64)''AppleWebKit/537.36(KHTML, like Gecko)''Chrome/61.0.3163.91''Safari/537.36'}
response = requests.get(url, headers=headers, proxies=prox_wrong)
print(response.text)

This is the results:

94.207.xxx.xx # My real IP

The request still goes trough and show my real IP address not the proxy.

How can I make sure that request stops if proxy not working or wrongly inserted? Thanks

Upvotes: 0

Views: 1374

Answers (1)

martin-martin
martin-martin

Reputation: 3564

I'm not sure what you mean with the comment about your proxy being all wrong. That said, you should provide the protocol with the IP address (docs)

It seems you are receiving a valid response from the proxy server - only that you can't access it without providing credentials:

<html>
<head>
  <title>407 Proxy Authentication Required</title>
</head>
<body>
  <h2>407 Proxy Authentication Required</h2>
  <h3>
    Access to requested resource disallowed by administrator or you
    need valid username/password to use this resource
  </h3>
</body>
</html>

So nothing seems to be fundamentally wrong.

If your proxy doesn't work, you'll probably receive a Timeout Exception.

In the event of a network problem (e.g. DNS failure, refused connection, etc), Requests will raise a ConnectionError exception. Response.raise_for_status() will raise an HTTPError if the HTTP request returned an unsuccessful status code. If a request times out, a Timeout exception is raised. If a request exceeds the configured number of maximum redirections, a TooManyRedirects exception is raised. All exceptions that Requests explicitly raises inherit from requests.exceptions.RequestException.

More in the docs source.

Upvotes: 1

Related Questions