|
14 | 14 |
|
15 | 15 |
|
16 | 16 | import io |
| 17 | +import ipaddress |
17 | 18 | import json |
18 | 19 | import re |
19 | 20 | import ssl |
| 21 | +from urllib.parse import urlparse |
| 22 | +from urllib.request import proxy_bypass_environment |
20 | 23 |
|
21 | 24 | import urllib3 |
22 | 25 |
|
@@ -100,7 +103,7 @@ def __init__(self, configuration) -> None: |
100 | 103 | # https pool manager |
101 | 104 | self.pool_manager: urllib3.PoolManager |
102 | 105 |
|
103 | | - if configuration.proxy: |
| 106 | + if configuration.proxy and not should_bypass_proxies(configuration.host, no_proxy=configuration.no_proxy or ''): |
104 | 107 | if is_socks_proxy_url(configuration.proxy): |
105 | 108 | from urllib3.contrib.socks import SOCKSProxyManager |
106 | 109 | pool_args["proxy_url"] = configuration.proxy |
@@ -257,3 +260,54 @@ def request( |
257 | 260 | raise ApiException(status=0, reason=msg) |
258 | 261 |
|
259 | 262 | return RESTResponse(r) |
| 263 | + |
| 264 | +def is_ipv4(target): |
| 265 | + """ Test if IPv4 address or not |
| 266 | + """ |
| 267 | + try: |
| 268 | + chk = ipaddress.IPv4Address(target) |
| 269 | + return True |
| 270 | + except ipaddress.AddressValueError: |
| 271 | + return False |
| 272 | + |
| 273 | +def in_ipv4net(target, net): |
| 274 | + """ Test if target belongs to given IPv4 network |
| 275 | + """ |
| 276 | + try: |
| 277 | + nw = ipaddress.IPv4Network(net) |
| 278 | + ip = ipaddress.IPv4Address(target) |
| 279 | + if ip in nw: |
| 280 | + return True |
| 281 | + return False |
| 282 | + except ipaddress.AddressValueError: |
| 283 | + return False |
| 284 | + except ipaddress.NetmaskValueError: |
| 285 | + return False |
| 286 | + |
| 287 | +def should_bypass_proxies(url, no_proxy=None): |
| 288 | + """ Yet another requests.should_bypass_proxies |
| 289 | + Test if proxies should not be used for a particular url. |
| 290 | + """ |
| 291 | + |
| 292 | + parsed = urlparse(url) |
| 293 | + |
| 294 | + # special cases |
| 295 | + if parsed.hostname in [None, '']: |
| 296 | + return True |
| 297 | + |
| 298 | + # special cases |
| 299 | + if no_proxy in [None , '']: |
| 300 | + return False |
| 301 | + if no_proxy == '*': |
| 302 | + return True |
| 303 | + |
| 304 | + no_proxy = no_proxy.lower().replace(' ',''); |
| 305 | + entries = ( |
| 306 | + host for host in no_proxy.split(',') if host |
| 307 | + ) |
| 308 | + |
| 309 | + if is_ipv4(parsed.hostname): |
| 310 | + for item in entries: |
| 311 | + if in_ipv4net(parsed.hostname, item): |
| 312 | + return True |
| 313 | + return proxy_bypass_environment(parsed.hostname, {'no': no_proxy} ) |
0 commit comments