poolmanager.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440
  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
  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. try:
  273. retries = retries.increment(method, url, response=response, _pool=conn)
  274. except MaxRetryError:
  275. if retries.raise_on_redirect:
  276. raise
  277. return response
  278. kw['retries'] = retries
  279. kw['redirect'] = redirect
  280. log.info("Redirecting %s -> %s", url, redirect_location)
  281. return self.urlopen(method, redirect_location, **kw)
  282. class ProxyManager(PoolManager):
  283. """
  284. Behaves just like :class:`PoolManager`, but sends all requests through
  285. the defined proxy, using the CONNECT method for HTTPS URLs.
  286. :param proxy_url:
  287. The URL of the proxy to be used.
  288. :param proxy_headers:
  289. A dictionary contaning headers that will be sent to the proxy. In case
  290. of HTTP they are being sent with each request, while in the
  291. HTTPS/CONNECT case they are sent only once. Could be used for proxy
  292. authentication.
  293. Example:
  294. >>> proxy = urllib3.ProxyManager('http://localhost:3128/')
  295. >>> r1 = proxy.request('GET', 'http://google.com/')
  296. >>> r2 = proxy.request('GET', 'http://httpbin.org/')
  297. >>> len(proxy.pools)
  298. 1
  299. >>> r3 = proxy.request('GET', 'https://httpbin.org/')
  300. >>> r4 = proxy.request('GET', 'https://twitter.com/')
  301. >>> len(proxy.pools)
  302. 3
  303. """
  304. def __init__(self, proxy_url, num_pools=10, headers=None,
  305. proxy_headers=None, **connection_pool_kw):
  306. if isinstance(proxy_url, HTTPConnectionPool):
  307. proxy_url = '%s://%s:%i' % (proxy_url.scheme, proxy_url.host,
  308. proxy_url.port)
  309. proxy = parse_url(proxy_url)
  310. if not proxy.port:
  311. port = port_by_scheme.get(proxy.scheme, 80)
  312. proxy = proxy._replace(port=port)
  313. if proxy.scheme not in ("http", "https"):
  314. raise ProxySchemeUnknown(proxy.scheme)
  315. self.proxy = proxy
  316. self.proxy_headers = proxy_headers or {}
  317. connection_pool_kw['_proxy'] = self.proxy
  318. connection_pool_kw['_proxy_headers'] = self.proxy_headers
  319. super(ProxyManager, self).__init__(
  320. num_pools, headers, **connection_pool_kw)
  321. def connection_from_host(self, host, port=None, scheme='http', pool_kwargs=None):
  322. if scheme == "https":
  323. return super(ProxyManager, self).connection_from_host(
  324. host, port, scheme, pool_kwargs=pool_kwargs)
  325. return super(ProxyManager, self).connection_from_host(
  326. self.proxy.host, self.proxy.port, self.proxy.scheme, pool_kwargs=pool_kwargs)
  327. def _set_proxy_headers(self, url, headers=None):
  328. """
  329. Sets headers needed by proxies: specifically, the Accept and Host
  330. headers. Only sets headers not provided by the user.
  331. """
  332. headers_ = {'Accept': '*/*'}
  333. netloc = parse_url(url).netloc
  334. if netloc:
  335. headers_['Host'] = netloc
  336. if headers:
  337. headers_.update(headers)
  338. return headers_
  339. def urlopen(self, method, url, redirect=True, **kw):
  340. "Same as HTTP(S)ConnectionPool.urlopen, ``url`` must be absolute."
  341. u = parse_url(url)
  342. if u.scheme == "http":
  343. # For proxied HTTPS requests, httplib sets the necessary headers
  344. # on the CONNECT to the proxy. For HTTP, we'll definitely
  345. # need to set 'Host' at the very least.
  346. headers = kw.get('headers', self.headers)
  347. kw['headers'] = self._set_proxy_headers(url, headers)
  348. return super(ProxyManager, self).urlopen(method, url, redirect=redirect, **kw)
  349. def proxy_from_url(url, **kw):
  350. return ProxyManager(proxy_url=url, **kw)