poolmanager.py 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280
  1. import logging
  2. try: # Python 3
  3. from urllib.parse import urljoin
  4. except ImportError:
  5. from urlparse import urljoin
  6. from ._collections import RecentlyUsedContainer
  7. from .connectionpool import HTTPConnectionPool, HTTPSConnectionPool
  8. from .connectionpool import port_by_scheme
  9. from .exceptions import LocationValueError, MaxRetryError
  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. pool_classes_by_scheme = {
  15. 'http': HTTPConnectionPool,
  16. 'https': HTTPSConnectionPool,
  17. }
  18. log = logging.getLogger(__name__)
  19. SSL_KEYWORDS = ('key_file', 'cert_file', 'cert_reqs', 'ca_certs',
  20. 'ssl_version')
  21. class PoolManager(RequestMethods):
  22. """
  23. Allows for arbitrary requests while transparently keeping track of
  24. necessary connection pools for you.
  25. :param num_pools:
  26. Number of connection pools to cache before discarding the least
  27. recently used pool.
  28. :param headers:
  29. Headers to include with all requests, unless other headers are given
  30. explicitly.
  31. :param \**connection_pool_kw:
  32. Additional parameters are used to create fresh
  33. :class:`urllib3.connectionpool.ConnectionPool` instances.
  34. Example::
  35. >>> manager = PoolManager(num_pools=2)
  36. >>> r = manager.request('GET', 'http://google.com/')
  37. >>> r = manager.request('GET', 'http://google.com/mail')
  38. >>> r = manager.request('GET', 'http://yahoo.com/')
  39. >>> len(manager.pools)
  40. 2
  41. """
  42. proxy = None
  43. def __init__(self, num_pools=10, headers=None, **connection_pool_kw):
  44. RequestMethods.__init__(self, headers)
  45. self.connection_pool_kw = connection_pool_kw
  46. self.pools = RecentlyUsedContainer(num_pools,
  47. dispose_func=lambda p: p.close())
  48. def __enter__(self):
  49. return self
  50. def __exit__(self, exc_type, exc_val, exc_tb):
  51. self.clear()
  52. # Return False to re-raise any potential exceptions
  53. return False
  54. def _new_pool(self, scheme, host, port):
  55. """
  56. Create a new :class:`ConnectionPool` based on host, port and scheme.
  57. This method is used to actually create the connection pools handed out
  58. by :meth:`connection_from_url` and companion methods. It is intended
  59. to be overridden for customization.
  60. """
  61. pool_cls = pool_classes_by_scheme[scheme]
  62. kwargs = self.connection_pool_kw
  63. if scheme == 'http':
  64. kwargs = self.connection_pool_kw.copy()
  65. for kw in SSL_KEYWORDS:
  66. kwargs.pop(kw, None)
  67. return pool_cls(host, port, **kwargs)
  68. def clear(self):
  69. """
  70. Empty our store of pools and direct them all to close.
  71. This will not affect in-flight connections, but they will not be
  72. re-used after completion.
  73. """
  74. self.pools.clear()
  75. def connection_from_host(self, host, port=None, scheme='http'):
  76. """
  77. Get a :class:`ConnectionPool` based on the host, port, and scheme.
  78. If ``port`` isn't given, it will be derived from the ``scheme`` using
  79. ``urllib3.connectionpool.port_by_scheme``.
  80. """
  81. if not host:
  82. raise LocationValueError("No host specified.")
  83. scheme = scheme or 'http'
  84. port = port or port_by_scheme.get(scheme, 80)
  85. pool_key = (scheme, host, port)
  86. with self.pools.lock:
  87. # If the scheme, host, or port doesn't match existing open
  88. # connections, open a new ConnectionPool.
  89. pool = self.pools.get(pool_key)
  90. if pool:
  91. return pool
  92. # Make a fresh ConnectionPool of the desired type
  93. pool = self._new_pool(scheme, host, port)
  94. self.pools[pool_key] = pool
  95. return pool
  96. def connection_from_url(self, url):
  97. """
  98. Similar to :func:`urllib3.connectionpool.connection_from_url` but
  99. doesn't pass any additional parameters to the
  100. :class:`urllib3.connectionpool.ConnectionPool` constructor.
  101. Additional parameters are taken from the :class:`.PoolManager`
  102. constructor.
  103. """
  104. u = parse_url(url)
  105. return self.connection_from_host(u.host, port=u.port, scheme=u.scheme)
  106. def urlopen(self, method, url, redirect=True, **kw):
  107. """
  108. Same as :meth:`urllib3.connectionpool.HTTPConnectionPool.urlopen`
  109. with custom cross-host redirect logic and only sends the request-uri
  110. portion of the ``url``.
  111. The given ``url`` parameter must be absolute, such that an appropriate
  112. :class:`urllib3.connectionpool.ConnectionPool` can be chosen for it.
  113. """
  114. u = parse_url(url)
  115. conn = self.connection_from_host(u.host, port=u.port, scheme=u.scheme)
  116. kw['assert_same_host'] = False
  117. kw['redirect'] = False
  118. if 'headers' not in kw:
  119. kw['headers'] = self.headers
  120. if self.proxy is not None and u.scheme == "http":
  121. response = conn.urlopen(method, url, **kw)
  122. else:
  123. response = conn.urlopen(method, u.request_uri, **kw)
  124. redirect_location = redirect and response.get_redirect_location()
  125. if not redirect_location:
  126. return response
  127. # Support relative URLs for redirecting.
  128. redirect_location = urljoin(url, redirect_location)
  129. # RFC 7231, Section 6.4.4
  130. if response.status == 303:
  131. method = 'GET'
  132. retries = kw.get('retries')
  133. if not isinstance(retries, Retry):
  134. retries = Retry.from_int(retries, redirect=redirect)
  135. try:
  136. retries = retries.increment(method, url, response=response, _pool=conn)
  137. except MaxRetryError:
  138. if retries.raise_on_redirect:
  139. raise
  140. return response
  141. kw['retries'] = retries
  142. kw['redirect'] = redirect
  143. log.info("Redirecting %s -> %s" % (url, redirect_location))
  144. return self.urlopen(method, redirect_location, **kw)
  145. class ProxyManager(PoolManager):
  146. """
  147. Behaves just like :class:`PoolManager`, but sends all requests through
  148. the defined proxy, using the CONNECT method for HTTPS URLs.
  149. :param proxy_url:
  150. The URL of the proxy to be used.
  151. :param proxy_headers:
  152. A dictionary contaning headers that will be sent to the proxy. In case
  153. of HTTP they are being sent with each request, while in the
  154. HTTPS/CONNECT case they are sent only once. Could be used for proxy
  155. authentication.
  156. Example:
  157. >>> proxy = urllib3.ProxyManager('http://localhost:3128/')
  158. >>> r1 = proxy.request('GET', 'http://google.com/')
  159. >>> r2 = proxy.request('GET', 'http://httpbin.org/')
  160. >>> len(proxy.pools)
  161. 1
  162. >>> r3 = proxy.request('GET', 'https://httpbin.org/')
  163. >>> r4 = proxy.request('GET', 'https://twitter.com/')
  164. >>> len(proxy.pools)
  165. 3
  166. """
  167. def __init__(self, proxy_url, num_pools=10, headers=None,
  168. proxy_headers=None, **connection_pool_kw):
  169. if isinstance(proxy_url, HTTPConnectionPool):
  170. proxy_url = '%s://%s:%i' % (proxy_url.scheme, proxy_url.host,
  171. proxy_url.port)
  172. proxy = parse_url(proxy_url)
  173. if not proxy.port:
  174. port = port_by_scheme.get(proxy.scheme, 80)
  175. proxy = proxy._replace(port=port)
  176. assert proxy.scheme in ("http", "https"), \
  177. 'Not supported proxy scheme %s' % proxy.scheme
  178. self.proxy = proxy
  179. self.proxy_headers = proxy_headers or {}
  180. connection_pool_kw['_proxy'] = self.proxy
  181. connection_pool_kw['_proxy_headers'] = self.proxy_headers
  182. super(ProxyManager, self).__init__(
  183. num_pools, headers, **connection_pool_kw)
  184. def connection_from_host(self, host, port=None, scheme='http'):
  185. if scheme == "https":
  186. return super(ProxyManager, self).connection_from_host(
  187. host, port, scheme)
  188. return super(ProxyManager, self).connection_from_host(
  189. self.proxy.host, self.proxy.port, self.proxy.scheme)
  190. def _set_proxy_headers(self, url, headers=None):
  191. """
  192. Sets headers needed by proxies: specifically, the Accept and Host
  193. headers. Only sets headers not provided by the user.
  194. """
  195. headers_ = {'Accept': '*/*'}
  196. netloc = parse_url(url).netloc
  197. if netloc:
  198. headers_['Host'] = netloc
  199. if headers:
  200. headers_.update(headers)
  201. return headers_
  202. def urlopen(self, method, url, redirect=True, **kw):
  203. "Same as HTTP(S)ConnectionPool.urlopen, ``url`` must be absolute."
  204. u = parse_url(url)
  205. if u.scheme == "http":
  206. # For proxied HTTPS requests, httplib sets the necessary headers
  207. # on the CONNECT to the proxy. For HTTP, we'll definitely
  208. # need to set 'Host' at the very least.
  209. headers = kw.get('headers', self.headers)
  210. kw['headers'] = self._set_proxy_headers(url, headers)
  211. return super(ProxyManager, self).urlopen(method, url, redirect=redirect, **kw)
  212. def proxy_from_url(url, **kw):
  213. return ProxyManager(proxy_url=url, **kw)