|
17 | 17 | import json |
18 | 18 | import re |
19 | 19 | import ssl |
| 20 | +from urllib.parse import urlparse |
| 21 | +from urllib.request import getproxies, proxy_bypass |
20 | 22 |
|
21 | 23 | import urllib3 |
22 | 24 |
|
@@ -100,14 +102,23 @@ def __init__(self, configuration) -> None: |
100 | 102 | # https pool manager |
101 | 103 | self.pool_manager: urllib3.PoolManager |
102 | 104 |
|
103 | | - if configuration.proxy: |
104 | | - if is_socks_proxy_url(configuration.proxy): |
| 105 | + parsed = urlparse(configuration.host) |
| 106 | + proxy = getproxies().get(parsed.scheme) if configuration.proxy is None else configuration.proxy |
| 107 | + if proxy: |
| 108 | + if configuration.no_proxy is not None: |
| 109 | + if _proxy_bypass(parsed.netloc, configuration.no_proxy): |
| 110 | + proxy = None |
| 111 | + elif proxy_bypass(parsed.netloc): |
| 112 | + proxy = None |
| 113 | + |
| 114 | + if proxy: |
| 115 | + if is_socks_proxy_url(proxy): |
105 | 116 | from urllib3.contrib.socks import SOCKSProxyManager |
106 | | - pool_args["proxy_url"] = configuration.proxy |
| 117 | + pool_args["proxy_url"] = proxy |
107 | 118 | pool_args["headers"] = configuration.proxy_headers |
108 | 119 | self.pool_manager = SOCKSProxyManager(**pool_args) |
109 | 120 | else: |
110 | | - pool_args["proxy_url"] = configuration.proxy |
| 121 | + pool_args["proxy_url"] = proxy |
111 | 122 | pool_args["proxy_headers"] = configuration.proxy_headers |
112 | 123 | self.pool_manager = urllib3.ProxyManager(**pool_args) |
113 | 124 | else: |
@@ -257,3 +268,27 @@ def request( |
257 | 268 | raise ApiException(status=0, reason=msg) |
258 | 269 |
|
259 | 270 | return RESTResponse(r) |
| 271 | + |
| 272 | +# Adapted from urllib.request.proxy_bypass_environment |
| 273 | +def _proxy_bypass(netloc: str, no_proxy: str): |
| 274 | + if no_proxy == '*': |
| 275 | + return True |
| 276 | + |
| 277 | + host = netloc.lower() |
| 278 | + if match := re.match(r'(.*):([0-9]*)', host): |
| 279 | + hostonly, _port = match.groups() |
| 280 | + else: |
| 281 | + hostonly = host |
| 282 | + |
| 283 | + for name in no_proxy.split(','): |
| 284 | + name = name.strip() |
| 285 | + if name: |
| 286 | + name = name.lstrip('.') |
| 287 | + name = name.lower() |
| 288 | + if hostonly == name or host == name: |
| 289 | + return True |
| 290 | + name = '.' + name |
| 291 | + if hostonly.endswith(name) or host.endswith(name): |
| 292 | + return True |
| 293 | + |
| 294 | + return False |
0 commit comments