PageRenderTime 59ms CodeModel.GetById 28ms RepoModel.GetById 0ms app.codeStats 0ms

/teca-env18/lib/python2.7/site-packages/pip/_vendor/urllib3/poolmanager.py

https://github.com/dpritsos/WEGA
Python | 449 lines | 308 code | 41 blank | 100 comment | 30 complexity | 2d766aa131e4f6254ffaf243a92f3c15 MD5 | raw file
  1. from __future__ import absolute_import
  2. import collections
  3. import functools
  4. import logging
  5. from ._collections import RecentlyUsedContainer
  6. from .connectionpool import HTTPConnectionPool, HTTPSConnectionPool
  7. from .connectionpool import port_by_scheme
  8. from .exceptions import LocationValueError, MaxRetryError, ProxySchemeUnknown
  9. from .packages.six.moves.urllib.parse import urljoin
  10. from .request import RequestMethods
  11. from .util.url import parse_url
  12. from .util.retry import Retry
  13. __all__ = ['PoolManager', 'ProxyManager', 'proxy_from_url']
  14. log = logging.getLogger(__name__)
  15. SSL_KEYWORDS = ('key_file', 'cert_file', 'cert_reqs', 'ca_certs',
  16. 'ssl_version', 'ca_cert_dir', 'ssl_context')
  17. # All known keyword arguments that could be provided to the pool manager, its
  18. # pools, or the underlying connections. This is used to construct a pool key.
  19. _key_fields = (
  20. 'key_scheme', # str
  21. 'key_host', # str
  22. 'key_port', # int
  23. 'key_timeout', # int or float or Timeout
  24. 'key_retries', # int or Retry
  25. 'key_strict', # bool
  26. 'key_block', # bool
  27. 'key_source_address', # str
  28. 'key_key_file', # str
  29. 'key_cert_file', # str
  30. 'key_cert_reqs', # str
  31. 'key_ca_certs', # str
  32. 'key_ssl_version', # str
  33. 'key_ca_cert_dir', # str
  34. 'key_ssl_context', # instance of ssl.SSLContext or urllib3.util.ssl_.SSLContext
  35. 'key_maxsize', # int
  36. 'key_headers', # dict
  37. 'key__proxy', # parsed proxy url
  38. 'key__proxy_headers', # dict
  39. 'key_socket_options', # list of (level (int), optname (int), value (int or str)) tuples
  40. 'key__socks_options', # dict
  41. 'key_assert_hostname', # bool or string
  42. 'key_assert_fingerprint', # str
  43. )
  44. #: The namedtuple class used to construct keys for the connection pool.
  45. #: All custom key schemes should include the fields in this key at a minimum.
  46. PoolKey = collections.namedtuple('PoolKey', _key_fields)
  47. def _default_key_normalizer(key_class, request_context):
  48. """
  49. Create a pool key out of a request context dictionary.
  50. According to RFC 3986, both the scheme and host are case-insensitive.
  51. Therefore, this function normalizes both before constructing the pool
  52. key for an HTTPS request. If you wish to change this behaviour, provide
  53. alternate callables to ``key_fn_by_scheme``.
  54. :param key_class:
  55. The class to use when constructing the key. This should be a namedtuple
  56. with the ``scheme`` and ``host`` keys at a minimum.
  57. :type key_class: namedtuple
  58. :param request_context:
  59. A dictionary-like object that contain the context for a request.
  60. :type request_context: dict
  61. :return: A namedtuple that can be used as a connection pool key.
  62. :rtype: PoolKey
  63. """
  64. # Since we mutate the dictionary, make a copy first
  65. context = request_context.copy()
  66. context['scheme'] = context['scheme'].lower()
  67. context['host'] = context['host'].lower()
  68. # These are both dictionaries and need to be transformed into frozensets
  69. for key in ('headers', '_proxy_headers', '_socks_options'):
  70. if key in context and context[key] is not None:
  71. context[key] = frozenset(context[key].items())
  72. # The socket_options key may be a list and needs to be transformed into a
  73. # tuple.
  74. socket_opts = context.get('socket_options')
  75. if socket_opts is not None:
  76. context['socket_options'] = tuple(socket_opts)
  77. # Map the kwargs to the names in the namedtuple - this is necessary since
  78. # namedtuples can't have fields starting with '_'.
  79. for key in list(context.keys()):
  80. context['key_' + key] = context.pop(key)
  81. # Default to ``None`` for keys missing from the context
  82. for field in key_class._fields:
  83. if field not in context:
  84. context[field] = None
  85. return key_class(**context)
  86. #: A dictionary that maps a scheme to a callable that creates a pool key.
  87. #: This can be used to alter the way pool keys are constructed, if desired.
  88. #: Each PoolManager makes a copy of this dictionary so they can be configured
  89. #: globally here, or individually on the instance.
  90. key_fn_by_scheme = {
  91. 'http': functools.partial(_default_key_normalizer, PoolKey),
  92. 'https': functools.partial(_default_key_normalizer, PoolKey),
  93. }
  94. pool_classes_by_scheme = {
  95. 'http': HTTPConnectionPool,
  96. 'https': HTTPSConnectionPool,
  97. }
  98. class PoolManager(RequestMethods):
  99. """
  100. Allows for arbitrary requests while transparently keeping track of
  101. necessary connection pools for you.
  102. :param num_pools:
  103. Number of connection pools to cache before discarding the least
  104. recently used pool.
  105. :param headers:
  106. Headers to include with all requests, unless other headers are given
  107. explicitly.
  108. :param \\**connection_pool_kw:
  109. Additional parameters are used to create fresh
  110. :class:`urllib3.connectionpool.ConnectionPool` instances.
  111. Example::
  112. >>> manager = PoolManager(num_pools=2)
  113. >>> r = manager.request('GET', 'http://google.com/')
  114. >>> r = manager.request('GET', 'http://google.com/mail')
  115. >>> r = manager.request('GET', 'http://yahoo.com/')
  116. >>> len(manager.pools)
  117. 2
  118. """
  119. proxy = None
  120. def __init__(self, num_pools=10, headers=None, **connection_pool_kw):
  121. RequestMethods.__init__(self, headers)
  122. self.connection_pool_kw = connection_pool_kw
  123. self.pools = RecentlyUsedContainer(num_pools,
  124. dispose_func=lambda p: p.close())
  125. # Locally set the pool classes and keys so other PoolManagers can
  126. # override them.
  127. self.pool_classes_by_scheme = pool_classes_by_scheme
  128. self.key_fn_by_scheme = key_fn_by_scheme.copy()
  129. def __enter__(self):
  130. return self
  131. def __exit__(self, exc_type, exc_val, exc_tb):
  132. self.clear()
  133. # Return False to re-raise any potential exceptions
  134. return False
  135. def _new_pool(self, scheme, host, port, request_context=None):
  136. """
  137. Create a new :class:`ConnectionPool` based on host, port, scheme, and
  138. any additional pool keyword arguments.
  139. If ``request_context`` is provided, it is provided as keyword arguments
  140. to the pool class used. This method is used to actually create the
  141. connection pools handed out by :meth:`connection_from_url` and
  142. companion methods. It is intended to be overridden for customization.
  143. """
  144. pool_cls = self.pool_classes_by_scheme[scheme]
  145. if request_context is None:
  146. request_context = self.connection_pool_kw.copy()
  147. # Although the context has everything necessary to create the pool,
  148. # this function has historically only used the scheme, host, and port
  149. # in the positional args. When an API change is acceptable these can
  150. # be removed.
  151. for key in ('scheme', 'host', 'port'):
  152. request_context.pop(key, None)
  153. if scheme == 'http':
  154. for kw in SSL_KEYWORDS:
  155. request_context.pop(kw, None)
  156. return pool_cls(host, port, **request_context)
  157. def clear(self):
  158. """
  159. Empty our store of pools and direct them all to close.
  160. This will not affect in-flight connections, but they will not be
  161. re-used after completion.
  162. """
  163. self.pools.clear()
  164. def connection_from_host(self, host, port=None, scheme='http', pool_kwargs=None):
  165. """
  166. Get a :class:`ConnectionPool` based on the host, port, and scheme.
  167. If ``port`` isn't given, it will be derived from the ``scheme`` using
  168. ``urllib3.connectionpool.port_by_scheme``. If ``pool_kwargs`` is
  169. provided, it is merged with the instance's ``connection_pool_kw``
  170. variable and used to create the new connection pool, if one is
  171. needed.
  172. """
  173. if not host:
  174. raise LocationValueError("No host specified.")
  175. request_context = self._merge_pool_kwargs(pool_kwargs)
  176. request_context['scheme'] = scheme or 'http'
  177. if not port:
  178. port = port_by_scheme.get(request_context['scheme'].lower(), 80)
  179. request_context['port'] = port
  180. request_context['host'] = host
  181. return self.connection_from_context(request_context)
  182. def connection_from_context(self, request_context):
  183. """
  184. Get a :class:`ConnectionPool` based on the request context.
  185. ``request_context`` must at least contain the ``scheme`` key and its
  186. value must be a key in ``key_fn_by_scheme`` instance variable.
  187. """
  188. scheme = request_context['scheme'].lower()
  189. pool_key_constructor = self.key_fn_by_scheme[scheme]
  190. pool_key = pool_key_constructor(request_context)
  191. return self.connection_from_pool_key(pool_key, request_context=request_context)
  192. def connection_from_pool_key(self, pool_key, request_context=None):
  193. """
  194. Get a :class:`ConnectionPool` based on the provided pool key.
  195. ``pool_key`` should be a namedtuple that only contains immutable
  196. objects. At a minimum it must have the ``scheme``, ``host``, and
  197. ``port`` fields.
  198. """
  199. with self.pools.lock:
  200. # If the scheme, host, or port doesn't match existing open
  201. # connections, open a new ConnectionPool.
  202. pool = self.pools.get(pool_key)
  203. if pool:
  204. return pool
  205. # Make a fresh ConnectionPool of the desired type
  206. scheme = request_context['scheme']
  207. host = request_context['host']
  208. port = request_context['port']
  209. pool = self._new_pool(scheme, host, port, request_context=request_context)
  210. self.pools[pool_key] = pool
  211. return pool
  212. def connection_from_url(self, url, pool_kwargs=None):
  213. """
  214. Similar to :func:`urllib3.connectionpool.connection_from_url`.
  215. If ``pool_kwargs`` is not provided and a new pool needs to be
  216. constructed, ``self.connection_pool_kw`` is used to initialize
  217. the :class:`urllib3.connectionpool.ConnectionPool`. If ``pool_kwargs``
  218. is provided, it is used instead. Note that if a new pool does not
  219. need to be created for the request, the provided ``pool_kwargs`` are
  220. not used.
  221. """
  222. u = parse_url(url)
  223. return self.connection_from_host(u.host, port=u.port, scheme=u.scheme,
  224. pool_kwargs=pool_kwargs)
  225. def _merge_pool_kwargs(self, override):
  226. """
  227. Merge a dictionary of override values for self.connection_pool_kw.
  228. This does not modify self.connection_pool_kw and returns a new dict.
  229. Any keys in the override dictionary with a value of ``None`` are
  230. removed from the merged dictionary.
  231. """
  232. base_pool_kwargs = self.connection_pool_kw.copy()
  233. if override:
  234. for key, value in override.items():
  235. if value is None:
  236. try:
  237. del base_pool_kwargs[key]
  238. except KeyError:
  239. pass
  240. else:
  241. base_pool_kwargs[key] = value
  242. return base_pool_kwargs
  243. def urlopen(self, method, url, redirect=True, **kw):
  244. """
  245. Same as :meth:`urllib3.connectionpool.HTTPConnectionPool.urlopen`
  246. with custom cross-host redirect logic and only sends the request-uri
  247. portion of the ``url``.
  248. The given ``url`` parameter must be absolute, such that an appropriate
  249. :class:`urllib3.connectionpool.ConnectionPool` can be chosen for it.
  250. """
  251. u = parse_url(url)
  252. conn = self.connection_from_host(u.host, port=u.port, scheme=u.scheme)
  253. kw['assert_same_host'] = False
  254. kw['redirect'] = False
  255. if 'headers' not in kw:
  256. kw['headers'] = self.headers.copy()
  257. if self.proxy is not None and u.scheme == "http":
  258. response = conn.urlopen(method, url, **kw)
  259. else:
  260. response = conn.urlopen(method, u.request_uri, **kw)
  261. redirect_location = redirect and response.get_redirect_location()
  262. if not redirect_location:
  263. return response
  264. # Support relative URLs for redirecting.
  265. redirect_location = urljoin(url, redirect_location)
  266. # RFC 7231, Section 6.4.4
  267. if response.status == 303:
  268. method = 'GET'
  269. retries = kw.get('retries')
  270. if not isinstance(retries, Retry):
  271. retries = Retry.from_int(retries, redirect=redirect)
  272. # Strip headers marked as unsafe to forward to the redirected location.
  273. # Check remove_headers_on_redirect to avoid a potential network call within
  274. # conn.is_same_host() which may use socket.gethostbyname() in the future.
  275. if (retries.remove_headers_on_redirect
  276. and not conn.is_same_host(redirect_location)):
  277. for header in retries.remove_headers_on_redirect:
  278. kw['headers'].pop(header, None)
  279. try:
  280. retries = retries.increment(method, url, response=response, _pool=conn)
  281. except MaxRetryError:
  282. if retries.raise_on_redirect:
  283. raise
  284. return response
  285. kw['retries'] = retries
  286. kw['redirect'] = redirect
  287. log.info("Redirecting %s -> %s", url, redirect_location)
  288. return self.urlopen(method, redirect_location, **kw)
  289. class ProxyManager(PoolManager):
  290. """
  291. Behaves just like :class:`PoolManager`, but sends all requests through
  292. the defined proxy, using the CONNECT method for HTTPS URLs.
  293. :param proxy_url:
  294. The URL of the proxy to be used.
  295. :param proxy_headers:
  296. A dictionary containing headers that will be sent to the proxy. In case
  297. of HTTP they are being sent with each request, while in the
  298. HTTPS/CONNECT case they are sent only once. Could be used for proxy
  299. authentication.
  300. Example:
  301. >>> proxy = urllib3.ProxyManager('http://localhost:3128/')
  302. >>> r1 = proxy.request('GET', 'http://google.com/')
  303. >>> r2 = proxy.request('GET', 'http://httpbin.org/')
  304. >>> len(proxy.pools)
  305. 1
  306. >>> r3 = proxy.request('GET', 'https://httpbin.org/')
  307. >>> r4 = proxy.request('GET', 'https://twitter.com/')
  308. >>> len(proxy.pools)
  309. 3
  310. """
  311. def __init__(self, proxy_url, num_pools=10, headers=None,
  312. proxy_headers=None, **connection_pool_kw):
  313. if isinstance(proxy_url, HTTPConnectionPool):
  314. proxy_url = '%s://%s:%i' % (proxy_url.scheme, proxy_url.host,
  315. proxy_url.port)
  316. proxy = parse_url(proxy_url)
  317. if not proxy.port:
  318. port = port_by_scheme.get(proxy.scheme, 80)
  319. proxy = proxy._replace(port=port)
  320. if proxy.scheme not in ("http", "https"):
  321. raise ProxySchemeUnknown(proxy.scheme)
  322. self.proxy = proxy
  323. self.proxy_headers = proxy_headers or {}
  324. connection_pool_kw['_proxy'] = self.proxy
  325. connection_pool_kw['_proxy_headers'] = self.proxy_headers
  326. super(ProxyManager, self).__init__(
  327. num_pools, headers, **connection_pool_kw)
  328. def connection_from_host(self, host, port=None, scheme='http', pool_kwargs=None):
  329. if scheme == "https":
  330. return super(ProxyManager, self).connection_from_host(
  331. host, port, scheme, pool_kwargs=pool_kwargs)
  332. return super(ProxyManager, self).connection_from_host(
  333. self.proxy.host, self.proxy.port, self.proxy.scheme, pool_kwargs=pool_kwargs)
  334. def _set_proxy_headers(self, url, headers=None):
  335. """
  336. Sets headers needed by proxies: specifically, the Accept and Host
  337. headers. Only sets headers not provided by the user.
  338. """
  339. headers_ = {'Accept': '*/*'}
  340. netloc = parse_url(url).netloc
  341. if netloc:
  342. headers_['Host'] = netloc
  343. if headers:
  344. headers_.update(headers)
  345. return headers_
  346. def urlopen(self, method, url, redirect=True, **kw):
  347. "Same as HTTP(S)ConnectionPool.urlopen, ``url`` must be absolute."
  348. u = parse_url(url)
  349. if u.scheme == "http":
  350. # For proxied HTTPS requests, httplib sets the necessary headers
  351. # on the CONNECT to the proxy. For HTTP, we'll definitely
  352. # need to set 'Host' at the very least.
  353. headers = kw.get('headers', self.headers)
  354. kw['headers'] = self._set_proxy_headers(url, headers)
  355. return super(ProxyManager, self).urlopen(method, url, redirect=redirect, **kw)
  356. def proxy_from_url(url, **kw):
  357. return ProxyManager(proxy_url=url, **kw)