Path: blob/master/venv/Lib/site-packages/requests/adapters.py
811 views
# -*- coding: utf-8 -*-12"""3requests.adapters4~~~~~~~~~~~~~~~~~56This module contains the transport adapters that Requests uses to define7and maintain connections.8"""910import os.path11import socket1213from urllib3.poolmanager import PoolManager, proxy_from_url14from urllib3.response import HTTPResponse15from urllib3.util import parse_url16from urllib3.util import Timeout as TimeoutSauce17from urllib3.util.retry import Retry18from urllib3.exceptions import ClosedPoolError19from urllib3.exceptions import ConnectTimeoutError20from urllib3.exceptions import HTTPError as _HTTPError21from urllib3.exceptions import MaxRetryError22from urllib3.exceptions import NewConnectionError23from urllib3.exceptions import ProxyError as _ProxyError24from urllib3.exceptions import ProtocolError25from urllib3.exceptions import ReadTimeoutError26from urllib3.exceptions import SSLError as _SSLError27from urllib3.exceptions import ResponseError28from urllib3.exceptions import LocationValueError2930from .models import Response31from .compat import urlparse, basestring32from .utils import (DEFAULT_CA_BUNDLE_PATH, extract_zipped_paths,33get_encoding_from_headers, prepend_scheme_if_needed,34get_auth_from_url, urldefragauth, select_proxy)35from .structures import CaseInsensitiveDict36from .cookies import extract_cookies_to_jar37from .exceptions import (ConnectionError, ConnectTimeout, ReadTimeout, SSLError,38ProxyError, RetryError, InvalidSchema, InvalidProxyURL,39InvalidURL)40from .auth import _basic_auth_str4142try:43from urllib3.contrib.socks import SOCKSProxyManager44except ImportError:45def SOCKSProxyManager(*args, **kwargs):46raise InvalidSchema("Missing dependencies for SOCKS support.")4748DEFAULT_POOLBLOCK = False49DEFAULT_POOLSIZE = 1050DEFAULT_RETRIES = 051DEFAULT_POOL_TIMEOUT = None525354class BaseAdapter(object):55"""The Base Transport Adapter"""5657def __init__(self):58super(BaseAdapter, self).__init__()5960def send(self, request, stream=False, timeout=None, verify=True,61cert=None, proxies=None):62"""Sends PreparedRequest object. Returns Response object.6364:param request: The :class:`PreparedRequest <PreparedRequest>` being sent.65:param stream: (optional) Whether to stream the request content.66:param timeout: (optional) How long to wait for the server to send67data before giving up, as a float, or a :ref:`(connect timeout,68read timeout) <timeouts>` tuple.69:type timeout: float or tuple70:param verify: (optional) Either a boolean, in which case it controls whether we verify71the server's TLS certificate, or a string, in which case it must be a path72to a CA bundle to use73:param cert: (optional) Any user-provided SSL certificate to be trusted.74:param proxies: (optional) The proxies dictionary to apply to the request.75"""76raise NotImplementedError7778def close(self):79"""Cleans up adapter specific items."""80raise NotImplementedError818283class HTTPAdapter(BaseAdapter):84"""The built-in HTTP Adapter for urllib3.8586Provides a general-case interface for Requests sessions to contact HTTP and87HTTPS urls by implementing the Transport Adapter interface. This class will88usually be created by the :class:`Session <Session>` class under the89covers.9091:param pool_connections: The number of urllib3 connection pools to cache.92:param pool_maxsize: The maximum number of connections to save in the pool.93:param max_retries: The maximum number of retries each connection94should attempt. Note, this applies only to failed DNS lookups, socket95connections and connection timeouts, never to requests where data has96made it to the server. By default, Requests does not retry failed97connections. If you need granular control over the conditions under98which we retry a request, import urllib3's ``Retry`` class and pass99that instead.100:param pool_block: Whether the connection pool should block for connections.101102Usage::103104>>> import requests105>>> s = requests.Session()106>>> a = requests.adapters.HTTPAdapter(max_retries=3)107>>> s.mount('http://', a)108"""109__attrs__ = ['max_retries', 'config', '_pool_connections', '_pool_maxsize',110'_pool_block']111112def __init__(self, pool_connections=DEFAULT_POOLSIZE,113pool_maxsize=DEFAULT_POOLSIZE, max_retries=DEFAULT_RETRIES,114pool_block=DEFAULT_POOLBLOCK):115if max_retries == DEFAULT_RETRIES:116self.max_retries = Retry(0, read=False)117else:118self.max_retries = Retry.from_int(max_retries)119self.config = {}120self.proxy_manager = {}121122super(HTTPAdapter, self).__init__()123124self._pool_connections = pool_connections125self._pool_maxsize = pool_maxsize126self._pool_block = pool_block127128self.init_poolmanager(pool_connections, pool_maxsize, block=pool_block)129130def __getstate__(self):131return {attr: getattr(self, attr, None) for attr in self.__attrs__}132133def __setstate__(self, state):134# Can't handle by adding 'proxy_manager' to self.__attrs__ because135# self.poolmanager uses a lambda function, which isn't pickleable.136self.proxy_manager = {}137self.config = {}138139for attr, value in state.items():140setattr(self, attr, value)141142self.init_poolmanager(self._pool_connections, self._pool_maxsize,143block=self._pool_block)144145def init_poolmanager(self, connections, maxsize, block=DEFAULT_POOLBLOCK, **pool_kwargs):146"""Initializes a urllib3 PoolManager.147148This method should not be called from user code, and is only149exposed for use when subclassing the150:class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.151152:param connections: The number of urllib3 connection pools to cache.153:param maxsize: The maximum number of connections to save in the pool.154:param block: Block when no free connections are available.155:param pool_kwargs: Extra keyword arguments used to initialize the Pool Manager.156"""157# save these values for pickling158self._pool_connections = connections159self._pool_maxsize = maxsize160self._pool_block = block161162self.poolmanager = PoolManager(num_pools=connections, maxsize=maxsize,163block=block, strict=True, **pool_kwargs)164165def proxy_manager_for(self, proxy, **proxy_kwargs):166"""Return urllib3 ProxyManager for the given proxy.167168This method should not be called from user code, and is only169exposed for use when subclassing the170:class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.171172:param proxy: The proxy to return a urllib3 ProxyManager for.173:param proxy_kwargs: Extra keyword arguments used to configure the Proxy Manager.174:returns: ProxyManager175:rtype: urllib3.ProxyManager176"""177if proxy in self.proxy_manager:178manager = self.proxy_manager[proxy]179elif proxy.lower().startswith('socks'):180username, password = get_auth_from_url(proxy)181manager = self.proxy_manager[proxy] = SOCKSProxyManager(182proxy,183username=username,184password=password,185num_pools=self._pool_connections,186maxsize=self._pool_maxsize,187block=self._pool_block,188**proxy_kwargs189)190else:191proxy_headers = self.proxy_headers(proxy)192manager = self.proxy_manager[proxy] = proxy_from_url(193proxy,194proxy_headers=proxy_headers,195num_pools=self._pool_connections,196maxsize=self._pool_maxsize,197block=self._pool_block,198**proxy_kwargs)199200return manager201202def cert_verify(self, conn, url, verify, cert):203"""Verify a SSL certificate. This method should not be called from user204code, and is only exposed for use when subclassing the205:class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.206207:param conn: The urllib3 connection object associated with the cert.208:param url: The requested URL.209:param verify: Either a boolean, in which case it controls whether we verify210the server's TLS certificate, or a string, in which case it must be a path211to a CA bundle to use212:param cert: The SSL certificate to verify.213"""214if url.lower().startswith('https') and verify:215216cert_loc = None217218# Allow self-specified cert location.219if verify is not True:220cert_loc = verify221222if not cert_loc:223cert_loc = extract_zipped_paths(DEFAULT_CA_BUNDLE_PATH)224225if not cert_loc or not os.path.exists(cert_loc):226raise IOError("Could not find a suitable TLS CA certificate bundle, "227"invalid path: {}".format(cert_loc))228229conn.cert_reqs = 'CERT_REQUIRED'230231if not os.path.isdir(cert_loc):232conn.ca_certs = cert_loc233else:234conn.ca_cert_dir = cert_loc235else:236conn.cert_reqs = 'CERT_NONE'237conn.ca_certs = None238conn.ca_cert_dir = None239240if cert:241if not isinstance(cert, basestring):242conn.cert_file = cert[0]243conn.key_file = cert[1]244else:245conn.cert_file = cert246conn.key_file = None247if conn.cert_file and not os.path.exists(conn.cert_file):248raise IOError("Could not find the TLS certificate file, "249"invalid path: {}".format(conn.cert_file))250if conn.key_file and not os.path.exists(conn.key_file):251raise IOError("Could not find the TLS key file, "252"invalid path: {}".format(conn.key_file))253254def build_response(self, req, resp):255"""Builds a :class:`Response <requests.Response>` object from a urllib3256response. This should not be called from user code, and is only exposed257for use when subclassing the258:class:`HTTPAdapter <requests.adapters.HTTPAdapter>`259260:param req: The :class:`PreparedRequest <PreparedRequest>` used to generate the response.261:param resp: The urllib3 response object.262:rtype: requests.Response263"""264response = Response()265266# Fallback to None if there's no status_code, for whatever reason.267response.status_code = getattr(resp, 'status', None)268269# Make headers case-insensitive.270response.headers = CaseInsensitiveDict(getattr(resp, 'headers', {}))271272# Set encoding.273response.encoding = get_encoding_from_headers(response.headers)274response.raw = resp275response.reason = response.raw.reason276277if isinstance(req.url, bytes):278response.url = req.url.decode('utf-8')279else:280response.url = req.url281282# Add new cookies from the server.283extract_cookies_to_jar(response.cookies, req, resp)284285# Give the Response some context.286response.request = req287response.connection = self288289return response290291def get_connection(self, url, proxies=None):292"""Returns a urllib3 connection for the given URL. This should not be293called from user code, and is only exposed for use when subclassing the294:class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.295296:param url: The URL to connect to.297:param proxies: (optional) A Requests-style dictionary of proxies used on this request.298:rtype: urllib3.ConnectionPool299"""300proxy = select_proxy(url, proxies)301302if proxy:303proxy = prepend_scheme_if_needed(proxy, 'http')304proxy_url = parse_url(proxy)305if not proxy_url.host:306raise InvalidProxyURL("Please check proxy URL. It is malformed"307" and could be missing the host.")308proxy_manager = self.proxy_manager_for(proxy)309conn = proxy_manager.connection_from_url(url)310else:311# Only scheme should be lower case312parsed = urlparse(url)313url = parsed.geturl()314conn = self.poolmanager.connection_from_url(url)315316return conn317318def close(self):319"""Disposes of any internal state.320321Currently, this closes the PoolManager and any active ProxyManager,322which closes any pooled connections.323"""324self.poolmanager.clear()325for proxy in self.proxy_manager.values():326proxy.clear()327328def request_url(self, request, proxies):329"""Obtain the url to use when making the final request.330331If the message is being sent through a HTTP proxy, the full URL has to332be used. Otherwise, we should only use the path portion of the URL.333334This should not be called from user code, and is only exposed for use335when subclassing the336:class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.337338:param request: The :class:`PreparedRequest <PreparedRequest>` being sent.339:param proxies: A dictionary of schemes or schemes and hosts to proxy URLs.340:rtype: str341"""342proxy = select_proxy(request.url, proxies)343scheme = urlparse(request.url).scheme344345is_proxied_http_request = (proxy and scheme != 'https')346using_socks_proxy = False347if proxy:348proxy_scheme = urlparse(proxy).scheme.lower()349using_socks_proxy = proxy_scheme.startswith('socks')350351url = request.path_url352if is_proxied_http_request and not using_socks_proxy:353url = urldefragauth(request.url)354355return url356357def add_headers(self, request, **kwargs):358"""Add any headers needed by the connection. As of v2.0 this does359nothing by default, but is left for overriding by users that subclass360the :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.361362This should not be called from user code, and is only exposed for use363when subclassing the364:class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.365366:param request: The :class:`PreparedRequest <PreparedRequest>` to add headers to.367:param kwargs: The keyword arguments from the call to send().368"""369pass370371def proxy_headers(self, proxy):372"""Returns a dictionary of the headers to add to any request sent373through a proxy. This works with urllib3 magic to ensure that they are374correctly sent to the proxy, rather than in a tunnelled request if375CONNECT is being used.376377This should not be called from user code, and is only exposed for use378when subclassing the379:class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.380381:param proxy: The url of the proxy being used for this request.382:rtype: dict383"""384headers = {}385username, password = get_auth_from_url(proxy)386387if username:388headers['Proxy-Authorization'] = _basic_auth_str(username,389password)390391return headers392393def send(self, request, stream=False, timeout=None, verify=True, cert=None, proxies=None):394"""Sends PreparedRequest object. Returns Response object.395396:param request: The :class:`PreparedRequest <PreparedRequest>` being sent.397:param stream: (optional) Whether to stream the request content.398:param timeout: (optional) How long to wait for the server to send399data before giving up, as a float, or a :ref:`(connect timeout,400read timeout) <timeouts>` tuple.401:type timeout: float or tuple or urllib3 Timeout object402:param verify: (optional) Either a boolean, in which case it controls whether403we verify the server's TLS certificate, or a string, in which case it404must be a path to a CA bundle to use405:param cert: (optional) Any user-provided SSL certificate to be trusted.406:param proxies: (optional) The proxies dictionary to apply to the request.407:rtype: requests.Response408"""409410try:411conn = self.get_connection(request.url, proxies)412except LocationValueError as e:413raise InvalidURL(e, request=request)414415self.cert_verify(conn, request.url, verify, cert)416url = self.request_url(request, proxies)417self.add_headers(request, stream=stream, timeout=timeout, verify=verify, cert=cert, proxies=proxies)418419chunked = not (request.body is None or 'Content-Length' in request.headers)420421if isinstance(timeout, tuple):422try:423connect, read = timeout424timeout = TimeoutSauce(connect=connect, read=read)425except ValueError as e:426# this may raise a string formatting error.427err = ("Invalid timeout {}. Pass a (connect, read) "428"timeout tuple, or a single float to set "429"both timeouts to the same value".format(timeout))430raise ValueError(err)431elif isinstance(timeout, TimeoutSauce):432pass433else:434timeout = TimeoutSauce(connect=timeout, read=timeout)435436try:437if not chunked:438resp = conn.urlopen(439method=request.method,440url=url,441body=request.body,442headers=request.headers,443redirect=False,444assert_same_host=False,445preload_content=False,446decode_content=False,447retries=self.max_retries,448timeout=timeout449)450451# Send the request.452else:453if hasattr(conn, 'proxy_pool'):454conn = conn.proxy_pool455456low_conn = conn._get_conn(timeout=DEFAULT_POOL_TIMEOUT)457458try:459low_conn.putrequest(request.method,460url,461skip_accept_encoding=True)462463for header, value in request.headers.items():464low_conn.putheader(header, value)465466low_conn.endheaders()467468for i in request.body:469low_conn.send(hex(len(i))[2:].encode('utf-8'))470low_conn.send(b'\r\n')471low_conn.send(i)472low_conn.send(b'\r\n')473low_conn.send(b'0\r\n\r\n')474475# Receive the response from the server476try:477# For Python 2.7, use buffering of HTTP responses478r = low_conn.getresponse(buffering=True)479except TypeError:480# For compatibility with Python 3.3+481r = low_conn.getresponse()482483resp = HTTPResponse.from_httplib(484r,485pool=conn,486connection=low_conn,487preload_content=False,488decode_content=False489)490except:491# If we hit any problems here, clean up the connection.492# Then, reraise so that we can handle the actual exception.493low_conn.close()494raise495496except (ProtocolError, socket.error) as err:497raise ConnectionError(err, request=request)498499except MaxRetryError as e:500if isinstance(e.reason, ConnectTimeoutError):501# TODO: Remove this in 3.0.0: see #2811502if not isinstance(e.reason, NewConnectionError):503raise ConnectTimeout(e, request=request)504505if isinstance(e.reason, ResponseError):506raise RetryError(e, request=request)507508if isinstance(e.reason, _ProxyError):509raise ProxyError(e, request=request)510511if isinstance(e.reason, _SSLError):512# This branch is for urllib3 v1.22 and later.513raise SSLError(e, request=request)514515raise ConnectionError(e, request=request)516517except ClosedPoolError as e:518raise ConnectionError(e, request=request)519520except _ProxyError as e:521raise ProxyError(e)522523except (_SSLError, _HTTPError) as e:524if isinstance(e, _SSLError):525# This branch is for urllib3 versions earlier than v1.22526raise SSLError(e, request=request)527elif isinstance(e, ReadTimeoutError):528raise ReadTimeout(e, request=request)529else:530raise531532return self.build_response(request, resp)533534535