简体   繁体   中英

Bypass proxy if not available using python requests.Session()

I am creating a software which access a internet URL. This software will be used on 2 PCs, one of them is behind the proxy.

To access the URL through proxy I have written below code :

proxies = {'https': 'https://my.proxy.server:1111'}
s = requests.Session()
s.proxies.update(proxies)
loginResponse = s.post(loginUrl, data=login_data, headers= headers)

This code works well on the computer which is behind the proxy but on other computer(which can access internet without proxy) I get an error : Can't connect to proxy . This is understandable.

My question is How can i modify this code so that it can work on both computers? What i want is to implement something like this:

proxy_server = XXXX
s = requests.Session()
s.proxies.update(proxy_server)

    if proxy_server not available : 
      s = requests.Session()

loginResponse = s.post(loginUrl, data=login_data, headers= headers)

You can try to catch the proxy error like this:

proxy_server = XXXX
s = requests.Session()
s.proxies.update(proxy_server)

try:
    loginResponse = s.post(loginUrl, data=login_data, headers= headers)
except requests.exceptions.ProxyError as err:
    s = requests.Session()
    ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM