Home > Blockchain >  Script evaluates when proxy is set
Script evaluates when proxy is set

Time:06-08

So, I'm writing a python script which does a GET request and send some data. However, sometimes I wanna see if the script is sending the data correctly, so I have to manually edit the script and set proxy like this

proxy = {'https': 'https://127.0.0.1'}

....snipped....

r = requests.get(url, data, proxies=proxy)

That's work perfectly. But I'd like to reduce this amount of work. For this I've add the following code at the beginning of the script.

if url != "":

    proxy = input("Wanna set proxies? Y-N: ")
    if proxy == "y":
        proxy = {'https': 'https://127.0.0.1:8080'}
    else:
        print("      ***Proceeding without proxies***")

Consider that, after creating this peace of code, I've commented out the line proxy = {'https': 'https://127.0.0.1'} from the first snipped code.

What happens is this, if I chose Y and set a proxy, then the rest of the code down bellow works just fine, on the other hand, if I choose N, the code throws the following error

Wanna set proxies? Y-N: n
      ***Proceeding without proxies***
Traceback (most recent call last):
  File "/home/user/scripts/work.py", line 42, in <module>
    req = requests.get(url numeros, cookies=cookies, proxies=proxy, verify=False, allow_redirects=True)
  File "/usr/lib/python3/dist-packages/requests/api.py", line 76, in get
    return request('get', url, params=params, **kwargs)
  File "/usr/lib/python3/dist-packages/requests/api.py", line 61, in request
    return session.request(method=method, url=url, **kwargs)
  File "/usr/lib/python3/dist-packages/requests/sessions.py", line 532, in request
    settings = self.merge_environment_settings(
  File "/usr/lib/python3/dist-packages/requests/sessions.py", line 710, in merge_environment_settings
    no_proxy = proxies.get('no_proxy') if proxies is not None else None
AttributeError: 'str' object has no attribute 'get'

I was wondering how I can bypass this, in a way that both works when I either set proxy or not.

CodePudding user response:

As described in the comments, you should pass a dict type to requests.get() proxies argument.

In your case just define proxy to {"http": None} to prevent that.

proxy = input("Wanna set proxies? Y-N: ")
if proxy == "y":
    proxy = {'https': 'https://127.0.0.1:8080'}
else:
    proxy = {"https": None}
    print("      ***Proceeding without proxies***")

But for better practice don't use the same variable:

proxies = {"https": None}
proxy = input("Wanna set proxies? Y-N: ")
if proxy == "y":
    proxies = {'https': 'https://127.0.0.1:8080'}
else:
    print("      ***Proceeding without proxies***")
r = requests.get(url, data, proxies=proxies)
  • Related