adapters.py
This file
Path
requests/adapters.py
516 lines · 20.2 KiB · Python
Last changed by
Merge pull request #3927 from bagerard/raise_IOError_invalid_certificate_filesCory Benfieldbefore adoption993cbf5
History of this fileTake it
1# -*- coding: utf-8 -*-23"""4requests.adapters5~~~~~~~~~~~~~~~~~67This module contains the transport adapters that Requests uses to define8and maintain connections.9"""1011import os.path12import socket1314from .models import Response15from .packages.urllib3.poolmanager import PoolManager, proxy_from_url16from .packages.urllib3.response import HTTPResponse17from .packages.urllib3.util import Timeout as TimeoutSauce18from .packages.urllib3.util.retry import Retry19from .compat import urlparse, basestring20from .utils import (DEFAULT_CA_BUNDLE_PATH, get_encoding_from_headers,21 prepend_scheme_if_needed, get_auth_from_url, urldefragauth,22 select_proxy, to_native_string)23from .structures import CaseInsensitiveDict24from .packages.urllib3.exceptions import ClosedPoolError25from .packages.urllib3.exceptions import ConnectTimeoutError26from .packages.urllib3.exceptions import HTTPError as _HTTPError27from .packages.urllib3.exceptions import MaxRetryError28from .packages.urllib3.exceptions import NewConnectionError29from .packages.urllib3.exceptions import ProxyError as _ProxyError30from .packages.urllib3.exceptions import ProtocolError31from .packages.urllib3.exceptions import ReadTimeoutError32from .packages.urllib3.exceptions import SSLError as _SSLError33from .packages.urllib3.exceptions import ResponseError34from .cookies import extract_cookies_to_jar35from .exceptions import (ConnectionError, ConnectTimeout, ReadTimeout, SSLError,36 ProxyError, RetryError, InvalidSchema)37from .auth import _basic_auth_str3839try:40 from .packages.urllib3.contrib.socks import SOCKSProxyManager41except ImportError:42 def SOCKSProxyManager(*args, **kwargs):43 raise InvalidSchema("Missing dependencies for SOCKS support.")4445DEFAULT_POOLBLOCK = False46DEFAULT_POOLSIZE = 1047DEFAULT_RETRIES = 048DEFAULT_POOL_TIMEOUT = None495051class BaseAdapter(object):52 """The Base Transport Adapter"""5354 def __init__(self):55 super(BaseAdapter, self).__init__()5657 def send(self, request, stream=False, timeout=None, verify=True,58 cert=None, proxies=None):59 """Sends PreparedRequest object. Returns Response object.6061 :param request: The :class:`PreparedRequest <PreparedRequest>` being sent.62 :param stream: (optional) Whether to stream the request content.63 :param timeout: (optional) How long to wait for the server to send64 data before giving up, as a float, or a :ref:`(connect timeout,65 read timeout) <timeouts>` tuple.66 :type timeout: float or tuple67 :param verify: (optional) Either a boolean, in which case it controls whether we verify68 the server's TLS certificate, or a string, in which case it must be a path69 to a CA bundle to use70 :param cert: (optional) Any user-provided SSL certificate to be trusted.71 :param proxies: (optional) The proxies dictionary to apply to the request.72 """73 raise NotImplementedError7475 def close(self):76 """Cleans up adapter specific items."""77 raise NotImplementedError787980class HTTPAdapter(BaseAdapter):81 """The built-in HTTP Adapter for urllib3.8283 Provides a general-case interface for Requests sessions to contact HTTP and84 HTTPS urls by implementing the Transport Adapter interface. This class will85 usually be created by the :class:`Session <Session>` class under the86 covers.8788 :param pool_connections: The number of urllib3 connection pools to cache.89 :param pool_maxsize: The maximum number of connections to save in the pool.90 :param max_retries: The maximum number of retries each connection91 should attempt. Note, this applies only to failed DNS lookups, socket92 connections and connection timeouts, never to requests where data has93 made it to the server. By default, Requests does not retry failed94 connections. If you need granular control over the conditions under95 which we retry a request, import urllib3's ``Retry`` class and pass96 that instead.97 :param pool_block: Whether the connection pool should block for connections.9899 Usage::100101 >>> import requests102 >>> s = requests.Session()103 >>> a = requests.adapters.HTTPAdapter(max_retries=3)104 >>> s.mount('http://', a)105 """106 __attrs__ = ['max_retries', 'config', '_pool_connections', '_pool_maxsize',107 '_pool_block']108109 def __init__(self, pool_connections=DEFAULT_POOLSIZE,110 pool_maxsize=DEFAULT_POOLSIZE, max_retries=DEFAULT_RETRIES,111 pool_block=DEFAULT_POOLBLOCK):112 if max_retries == DEFAULT_RETRIES:113 self.max_retries = Retry(0, read=False)114 else:115 self.max_retries = Retry.from_int(max_retries)116 self.config = {}117 self.proxy_manager = {}118119 super(HTTPAdapter, self).__init__()120121 self._pool_connections = pool_connections122 self._pool_maxsize = pool_maxsize123 self._pool_block = pool_block124125 self.init_poolmanager(pool_connections, pool_maxsize, block=pool_block)126127 def __getstate__(self):128 return dict((attr, getattr(self, attr, None)) for attr in129 self.__attrs__)130131 def __setstate__(self, state):132 # Can't handle by adding 'proxy_manager' to self.__attrs__ because133 # self.poolmanager uses a lambda function, which isn't pickleable.134 self.proxy_manager = {}135 self.config = {}136137 for attr, value in state.items():138 setattr(self, attr, value)139140 self.init_poolmanager(self._pool_connections, self._pool_maxsize,141 block=self._pool_block)142143 def init_poolmanager(self, connections, maxsize, block=DEFAULT_POOLBLOCK, **pool_kwargs):144 """Initializes a urllib3 PoolManager.145146 This method should not be called from user code, and is only147 exposed for use when subclassing the148 :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.149150 :param connections: The number of urllib3 connection pools to cache.151 :param maxsize: The maximum number of connections to save in the pool.152 :param block: Block when no free connections are available.153 :param pool_kwargs: Extra keyword arguments used to initialize the Pool Manager.154 """155 # save these values for pickling156 self._pool_connections = connections157 self._pool_maxsize = maxsize158 self._pool_block = block159160 self.poolmanager = PoolManager(num_pools=connections, maxsize=maxsize,161 block=block, strict=True, **pool_kwargs)162163 def proxy_manager_for(self, proxy, **proxy_kwargs):164 """Return urllib3 ProxyManager for the given proxy.165166 This method should not be called from user code, and is only167 exposed for use when subclassing the168 :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.169170 :param proxy: The proxy to return a urllib3 ProxyManager for.171 :param proxy_kwargs: Extra keyword arguments used to configure the Proxy Manager.172 :returns: ProxyManager173 :rtype: requests.packages.urllib3.ProxyManager174 """175 if proxy in self.proxy_manager:176 manager = self.proxy_manager[proxy]177 elif proxy.lower().startswith('socks'):178 username, password = get_auth_from_url(proxy)179 manager = self.proxy_manager[proxy] = SOCKSProxyManager(180 proxy,181 username=username,182 password=password,183 num_pools=self._pool_connections,184 maxsize=self._pool_maxsize,185 block=self._pool_block,186 **proxy_kwargs187 )188 else:189 proxy_headers = self.proxy_headers(proxy)190 manager = self.proxy_manager[proxy] = proxy_from_url(191 proxy,192 proxy_headers=proxy_headers,193 num_pools=self._pool_connections,194 maxsize=self._pool_maxsize,195 block=self._pool_block,196 **proxy_kwargs)197198 return manager199200 def cert_verify(self, conn, url, verify, cert):201 """Verify a SSL certificate. This method should not be called from user202 code, and is only exposed for use when subclassing the203 :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.204205 :param conn: The urllib3 connection object associated with the cert.206 :param url: The requested URL.207 :param verify: Either a boolean, in which case it controls whether we verify208 the server's TLS certificate, or a string, in which case it must be a path209 to a CA bundle to use210 :param cert: The SSL certificate to verify.211 """212 if url.lower().startswith('https') and verify:213214 cert_loc = None215216 # Allow self-specified cert location.217 if verify is not True:218 cert_loc = verify219220 if not cert_loc:221 cert_loc = DEFAULT_CA_BUNDLE_PATH222223 if not cert_loc or not os.path.exists(cert_loc):224 raise IOError("Could not find a suitable TLS CA certificate bundle, "225 "invalid path: {0}".format(cert_loc))226227 conn.cert_reqs = 'CERT_REQUIRED'228229 if not os.path.isdir(cert_loc):230 conn.ca_certs = cert_loc231 else:232 conn.ca_cert_dir = cert_loc233 else:234 conn.cert_reqs = 'CERT_NONE'235 conn.ca_certs = None236 conn.ca_cert_dir = None237238 if cert:239 if not isinstance(cert, basestring):240 conn.cert_file = cert[0]241 conn.key_file = cert[1]242 else:243 conn.cert_file = cert244 if conn.cert_file and not os.path.exists(conn.cert_file):245 raise IOError("Could not find the TLS certificate file, "246 "invalid path: {0}".format(conn.cert_file))247 if conn.key_file and not os.path.exists(conn.key_file):248 raise IOError("Could not find the TLS key file, "249 "invalid path: {0}".format(conn.key_file))250251 def build_response(self, req, resp):252 """Builds a :class:`Response <requests.Response>` object from a urllib3253 response. This should not be called from user code, and is only exposed254 for use when subclassing the255 :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`256257 :param req: The :class:`PreparedRequest <PreparedRequest>` used to generate the response.258 :param resp: The urllib3 response object.259 :rtype: requests.Response260 """261 response = Response()262263 # Fallback to None if there's no status_code, for whatever reason.264 response.status_code = getattr(resp, 'status', None)265266 # Make headers case-insensitive.267 response.headers = CaseInsensitiveDict(getattr(resp, 'headers', {}))268269 # Set encoding.270 response.encoding = get_encoding_from_headers(response.headers)271 response.raw = resp272 response.reason = response.raw.reason273274 if isinstance(req.url, bytes):275 response.url = req.url.decode('utf-8')276 else:277 response.url = req.url278279 # Add new cookies from the server.280 extract_cookies_to_jar(response.cookies, req, resp)281282 # Give the Response some context.283 response.request = req284 response.connection = self285286 return response287288 def get_connection(self, url, proxies=None):289 """Returns a urllib3 connection for the given URL. This should not be290 called from user code, and is only exposed for use when subclassing the291 :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.292293 :param url: The URL to connect to.294 :param proxies: (optional) A Requests-style dictionary of proxies used on this request.295 :rtype: requests.packages.urllib3.ConnectionPool296 """297 proxy = select_proxy(url, proxies)298299 if proxy:300 proxy = prepend_scheme_if_needed(proxy, 'http')301 proxy_manager = self.proxy_manager_for(proxy)302 conn = proxy_manager.connection_from_url(url)303 else:304 # Only scheme should be lower case305 parsed = urlparse(url)306 url = parsed.geturl()307 conn = self.poolmanager.connection_from_url(url)308309 return conn310311 def close(self):312 """Disposes of any internal state.313314 Currently, this closes the PoolManager and any active ProxyManager,315 which closes any pooled connections.316 """317 self.poolmanager.clear()318 for proxy in self.proxy_manager.values():319 proxy.clear()320321 def request_url(self, request, proxies):322 """Obtain the url to use when making the final request.323324 If the message is being sent through a HTTP proxy, the full URL has to325 be used. Otherwise, we should only use the path portion of the URL.326327 This should not be called from user code, and is only exposed for use328 when subclassing the329 :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.330331 :param request: The :class:`PreparedRequest <PreparedRequest>` being sent.332 :param proxies: A dictionary of schemes or schemes and hosts to proxy URLs.333 :rtype: str334 """335 proxy = select_proxy(request.url, proxies)336 scheme = urlparse(request.url).scheme337338 is_proxied_http_request = (proxy and scheme != 'https')339 using_socks_proxy = False340 if proxy:341 proxy_scheme = urlparse(proxy).scheme.lower()342 using_socks_proxy = proxy_scheme.startswith('socks')343344 url = request.path_url345 if is_proxied_http_request and not using_socks_proxy:346 url = urldefragauth(request.url)347348 return url349350 def add_headers(self, request, **kwargs):351 """Add any headers needed by the connection. As of v2.0 this does352 nothing by default, but is left for overriding by users that subclass353 the :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.354355 This should not be called from user code, and is only exposed for use356 when subclassing the357 :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.358359 :param request: The :class:`PreparedRequest <PreparedRequest>` to add headers to.360 :param kwargs: The keyword arguments from the call to send().361 """362 pass363364 def proxy_headers(self, proxy):365 """Returns a dictionary of the headers to add to any request sent366 through a proxy. This works with urllib3 magic to ensure that they are367 correctly sent to the proxy, rather than in a tunnelled request if368 CONNECT is being used.369370 This should not be called from user code, and is only exposed for use371 when subclassing the372 :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.373374 :param proxies: The url of the proxy being used for this request.375 :rtype: dict376 """377 headers = {}378 username, password = get_auth_from_url(proxy)379380 if username:381 headers['Proxy-Authorization'] = _basic_auth_str(username,382 password)383384 return headers385386 def send(self, request, stream=False, timeout=None, verify=True, cert=None, proxies=None):387 """Sends PreparedRequest object. Returns Response object.388389 :param request: The :class:`PreparedRequest <PreparedRequest>` being sent.390 :param stream: (optional) Whether to stream the request content.391 :param timeout: (optional) How long to wait for the server to send392 data before giving up, as a float, or a :ref:`(connect timeout,393 read timeout) <timeouts>` tuple.394 :type timeout: float or tuple395 :param verify: (optional) Either a boolean, in which case it controls whether396 we verify the server's TLS certificate, or a string, in which case it397 must be a path to a CA bundle to use398 :param cert: (optional) Any user-provided SSL certificate to be trusted.399 :param proxies: (optional) The proxies dictionary to apply to the request.400 :rtype: requests.Response401 """402403 conn = self.get_connection(request.url, proxies)404405 self.cert_verify(conn, request.url, verify, cert)406 url = self.request_url(request, proxies)407 self.add_headers(request)408409 chunked = not (request.body is None or 'Content-Length' in request.headers)410411 if isinstance(timeout, tuple):412 try:413 connect, read = timeout414 timeout = TimeoutSauce(connect=connect, read=read)415 except ValueError as e:416 # this may raise a string formatting error.417 err = ("Invalid timeout {0}. Pass a (connect, read) "418 "timeout tuple, or a single float to set "419 "both timeouts to the same value".format(timeout))420 raise ValueError(err)421 else:422 timeout = TimeoutSauce(connect=timeout, read=timeout)423424 try:425 if not chunked:426 resp = conn.urlopen(427 method=request.method,428 url=url,429 body=request.body,430 headers=request.headers,431 redirect=False,432 assert_same_host=False,433 preload_content=False,434 decode_content=False,435 retries=self.max_retries,436 timeout=timeout437 )438439 # Send the request.440 else:441 if hasattr(conn, 'proxy_pool'):442 conn = conn.proxy_pool443444 low_conn = conn._get_conn(timeout=DEFAULT_POOL_TIMEOUT)445446 try:447 low_conn.putrequest(request.method,448 url,449 skip_accept_encoding=True)450451 for header, value in request.headers.items():452 low_conn.putheader(header, value)453454 low_conn.endheaders()455456 for i in request.body:457 low_conn.send(hex(len(i))[2:].encode('utf-8'))458 low_conn.send(b'\r\n')459 low_conn.send(i)460 low_conn.send(b'\r\n')461 low_conn.send(b'0\r\n\r\n')462463 # Receive the response from the server464 try:465 # For Python 2.7+ versions, use buffering of HTTP466 # responses467 r = low_conn.getresponse(buffering=True)468 except TypeError:469 # For compatibility with Python 2.6 versions and back470 r = low_conn.getresponse()471472 resp = HTTPResponse.from_httplib(473 r,474 pool=conn,475 connection=low_conn,476 preload_content=False,477 decode_content=False478 )479 except:480 # If we hit any problems here, clean up the connection.481 # Then, reraise so that we can handle the actual exception.482 low_conn.close()483 raise484485 except (ProtocolError, socket.error) as err:486 raise ConnectionError(err, request=request)487488 except MaxRetryError as e:489 if isinstance(e.reason, ConnectTimeoutError):490 # TODO: Remove this in 3.0.0: see #2811491 if not isinstance(e.reason, NewConnectionError):492 raise ConnectTimeout(e, request=request)493494 if isinstance(e.reason, ResponseError):495 raise RetryError(e, request=request)496497 if isinstance(e.reason, _ProxyError):498 raise ProxyError(e, request=request)499500 raise ConnectionError(e, request=request)501502 except ClosedPoolError as e:503 raise ConnectionError(e, request=request)504505 except _ProxyError as e:506 raise ProxyError(e)507508 except (_SSLError, _HTTPError) as e:509 if isinstance(e, _SSLError):510 raise SSLError(e, request=request)511 elif isinstance(e, ReadTimeoutError):512 raise ReadTimeout(e, request=request)513 else:514 raise515516 return self.build_response(request, resp)