fork download
  1. import requests
  2.  
  3.  
  4. def select_proxy(url, proxies):
  5. """Select a proxy for the url, if applicable.
  6.  
  7. :param url: The url being for the request
  8. :param proxies: A dictionary of schemes or schemes and hosts to proxy URLs
  9. """
  10. proxies = proxies or {}
  11. urlparts = requests.utils.urlparse(url)
  12. if urlparts.hostname is None:
  13. return proxies.get(urlparts.scheme, proxies.get('all'))
  14.  
  15. proxy = None
  16. if requests.utils.should_bypass_proxies(url, proxies.get('no_proxy')):
  17. return proxy
  18.  
  19. proxy_keys = [
  20. urlparts.scheme + '://' + urlparts.hostname,
  21. urlparts.scheme,
  22. 'all://' + urlparts.hostname,
  23. 'all',
  24. ]
  25.  
  26. for proxy_key in proxy_keys:
  27. if proxy_key in proxies:
  28. proxy = proxies[proxy_key]
  29. break
  30.  
  31. return proxy
  32.  
  33.  
  34. class NoProxyAdapter(requests.adapters.HTTPAdapter):
  35. def get_connection(self, url, proxies=None):
  36. """Returns a urllib3 connection for the given URL. This should not be
  37. called from user code, and is only exposed for use when subclassing the
  38. :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.
  39.  
  40. :param url: The URL to connect to.
  41. :param proxies: (optional) A Requests-style dictionary of proxies used on this request.
  42. :rtype: urllib3.ConnectionPool
  43. """
  44. proxy = select_proxy(url, proxies)
  45.  
  46. if proxy and proxy not in proxies.get('no_proxy', []):
  47. proxy = requests.adapters.prepend_scheme_if_needed(proxy, 'http')
  48. proxy_manager = self.proxy_manager_for(proxy)
  49. conn = proxy_manager.connection_from_url(url)
  50. else:
  51. # Only scheme should be lower case
  52. parsed = requests.adapters.urlparse(url)
  53. url = parsed.geturl()
  54. conn = self.poolmanager.connection_from_url(url)
  55.  
  56. return conn
  57.  
  58.  
  59. if __name__ == "__main__":
  60. s = requests.Session()
  61. s.mount('http://', NoProxyAdapter())
  62. r = requests.Request(url='http://127.0.0.2').prepare()
  63. s.send(
  64. r,
  65. proxies={
  66. 'http': 'http://127.0.0.1:8090',
  67. 'no_proxy': '127.0.0.2',
  68. },
  69. )
  70.  
Runtime error #stdin #stdout #stderr 0.04s 9320KB
stdin
Standard input is empty
stdout
Standard output is empty
stderr
Traceback (most recent call last):
  File "./prog.py", line 1, in <module>
ImportError: No module named 'requests'