| 1 |
|
| 2 |
|
| 3 |
""" |
| 4 |
requests.adapters |
| 5 |
~~~~~~~~~~~~~~~~~ |
| 6 |
|
| 7 |
This module contains the transport adapters that Requests uses to define |
| 8 |
and maintain connections. |
| 9 |
""" |
| 10 |
|
| 11 |
import socket |
| 12 |
|
| 13 |
from .models import Response |
| 14 |
from .packages.urllib3.poolmanager import PoolManager, ProxyManager |
| 15 |
from .packages.urllib3.response import HTTPResponse |
| 16 |
from .compat import urlparse, basestring, urldefrag, unquote |
| 17 |
from .utils import (DEFAULT_CA_BUNDLE_PATH, get_encoding_from_headers, |
| 18 |
prepend_scheme_if_needed, get_auth_from_url) |
| 19 |
from .structures import CaseInsensitiveDict |
| 20 |
from .packages.urllib3.exceptions import MaxRetryError |
| 21 |
from .packages.urllib3.exceptions import TimeoutError |
| 22 |
from .packages.urllib3.exceptions import SSLError as _SSLError |
| 23 |
from .packages.urllib3.exceptions import HTTPError as _HTTPError |
| 24 |
from .cookies import extract_cookies_to_jar |
| 25 |
from .exceptions import ConnectionError, Timeout, SSLError |
| 26 |
from .auth import _basic_auth_str |
| 27 |
|
| 28 |
DEFAULT_POOLSIZE = 10 |
| 29 |
DEFAULT_RETRIES = 0 |
| 30 |
|
| 31 |
|
| 32 |
class BaseAdapter(object): |
| 33 |
"""The Base Transport Adapter""" |
| 34 |
|
| 35 |
def __init__(self): |
| 36 |
super(BaseAdapter, self).__init__() |
| 37 |
|
| 38 |
def send(self): |
| 39 |
raise NotImplementedError |
| 40 |
|
| 41 |
def close(self): |
| 42 |
raise NotImplementedError |
| 43 |
|
| 44 |
|
| 45 |
class HTTPAdapter(BaseAdapter): |
| 46 |
"""Built-In HTTP Adapter for Urllib3.""" |
| 47 |
def __init__(self, pool_connections=DEFAULT_POOLSIZE, pool_maxsize=DEFAULT_POOLSIZE): |
| 48 |
self.max_retries = DEFAULT_RETRIES |
| 49 |
self.config = {} |
| 50 |
|
| 51 |
super(HTTPAdapter, self).__init__() |
| 52 |
|
| 53 |
self.init_poolmanager(pool_connections, pool_maxsize) |
| 54 |
|
| 55 |
def init_poolmanager(self, connections, maxsize): |
| 56 |
self.poolmanager = PoolManager(num_pools=connections, maxsize=maxsize) |
| 57 |
|
| 58 |
def cert_verify(self, conn, url, verify, cert): |
| 59 |
if url.startswith('https') and verify: |
| 60 |
|
| 61 |
cert_loc = None |
| 62 |
|
| 63 |
|
| 64 |
if verify is not True: |
| 65 |
cert_loc = verify |
| 66 |
|
| 67 |
if not cert_loc: |
| 68 |
cert_loc = DEFAULT_CA_BUNDLE_PATH |
| 69 |
|
| 70 |
if not cert_loc: |
| 71 |
raise Exception("Could not find a suitable SSL CA certificate bundle.") |
| 72 |
|
| 73 |
conn.cert_reqs = 'CERT_REQUIRED' |
| 74 |
conn.ca_certs = cert_loc |
| 75 |
else: |
| 76 |
conn.cert_reqs = 'CERT_NONE' |
| 77 |
conn.ca_certs = None |
| 78 |
|
| 79 |
if cert: |
| 80 |
if not isinstance(cert, basestring): |
| 81 |
conn.cert_file = cert[0] |
| 82 |
conn.key_file = cert[1] |
| 83 |
else: |
| 84 |
conn.cert_file = cert |
| 85 |
|
| 86 |
def build_response(self, req, resp): |
| 87 |
response = Response() |
| 88 |
|
| 89 |
|
| 90 |
response.status_code = getattr(resp, 'status', None) |
| 91 |
|
| 92 |
|
| 93 |
response.headers = CaseInsensitiveDict(getattr(resp, 'headers', {})) |
| 94 |
|
| 95 |
|
| 96 |
response.encoding = get_encoding_from_headers(response.headers) |
| 97 |
response.raw = resp |
| 98 |
response.reason = response.raw.reason |
| 99 |
|
| 100 |
if isinstance(req.url, bytes): |
| 101 |
response.url = req.url.decode('utf-8') |
| 102 |
else: |
| 103 |
response.url = req.url |
| 104 |
|
| 105 |
|
| 106 |
extract_cookies_to_jar(response.cookies, req, resp) |
| 107 |
|
| 108 |
|
| 109 |
response.request = req |
| 110 |
response.connection = self |
| 111 |
|
| 112 |
return response |
| 113 |
|
| 114 |
def get_connection(self, url, proxies=None): |
| 115 |
"""Returns a connection for the given URL.""" |
| 116 |
proxies = proxies or {} |
| 117 |
proxy = proxies.get(urlparse(url).scheme) |
| 118 |
|
| 119 |
if proxy: |
| 120 |
proxy = prepend_scheme_if_needed(proxy, urlparse(url).scheme) |
| 121 |
conn = ProxyManager(self.poolmanager.connection_from_url(proxy)) |
| 122 |
else: |
| 123 |
conn = self.poolmanager.connection_from_url(url) |
| 124 |
|
| 125 |
return conn |
| 126 |
|
| 127 |
def close(self): |
| 128 |
"""Dispose of any internal state. |
| 129 |
|
| 130 |
Currently, this just closes the PoolManager, which closes pooled |
| 131 |
connections. |
| 132 |
""" |
| 133 |
self.poolmanager.clear() |
| 134 |
|
| 135 |
def request_url(self, request, proxies): |
| 136 |
"""Obtain the url to use when making the final request. |
| 137 |
|
| 138 |
If the message is being sent through a proxy, the full URL has to be |
| 139 |
used. Otherwise, we should only use the path portion of the URL.""" |
| 140 |
proxies = proxies or {} |
| 141 |
proxy = proxies.get(urlparse(request.url).scheme) |
| 142 |
|
| 143 |
if proxy: |
| 144 |
url, _ = urldefrag(request.url) |
| 145 |
else: |
| 146 |
url = request.path_url |
| 147 |
|
| 148 |
return url |
| 149 |
|
| 150 |
def add_headers(self, request, **kwargs): |
| 151 |
"""Add any headers needed by the connection. Currently this adds a |
| 152 |
Proxy-Authorization header.""" |
| 153 |
proxies = kwargs.get('proxies', {}) |
| 154 |
|
| 155 |
if proxies is None: |
| 156 |
proxies = {} |
| 157 |
|
| 158 |
proxy = proxies.get(urlparse(request.url).scheme) |
| 159 |
username, password = get_auth_from_url(proxy) |
| 160 |
|
| 161 |
if username and password: |
| 162 |
|
| 163 |
|
| 164 |
username = unquote(username) |
| 165 |
password = unquote(password) |
| 166 |
request.headers['Proxy-Authorization'] = _basic_auth_str(username, |
| 167 |
password) |
| 168 |
|
| 169 |
def send(self, request, stream=False, timeout=None, verify=True, cert=None, proxies=None): |
| 170 |
"""Sends PreparedRequest object. Returns Response object.""" |
| 171 |
|
| 172 |
conn = self.get_connection(request.url, proxies) |
| 173 |
|
| 174 |
self.cert_verify(conn, request.url, verify, cert) |
| 175 |
url = self.request_url(request, proxies) |
| 176 |
self.add_headers(request, proxies=proxies) |
| 177 |
|
| 178 |
chunked = not (request.body is None or 'Content-Length' in request.headers) |
| 179 |
|
| 180 |
try: |
| 181 |
if not chunked: |
| 182 |
resp = conn.urlopen( |
| 183 |
method=request.method, |
| 184 |
url=url, |
| 185 |
body=request.body, |
| 186 |
headers=request.headers, |
| 187 |
redirect=False, |
| 188 |
assert_same_host=False, |
| 189 |
preload_content=False, |
| 190 |
decode_content=False, |
| 191 |
retries=self.max_retries, |
| 192 |
timeout=timeout |
| 193 |
) |
| 194 |
|
| 195 |
|
| 196 |
else: |
| 197 |
if hasattr(conn, 'proxy_pool'): |
| 198 |
conn = conn.proxy_pool |
| 199 |
|
| 200 |
low_conn = conn._get_conn(timeout=timeout) |
| 201 |
low_conn.putrequest(request.method, url, skip_accept_encoding=True) |
| 202 |
|
| 203 |
for header, value in request.headers.items(): |
| 204 |
low_conn.putheader(header, value) |
| 205 |
|
| 206 |
low_conn.endheaders() |
| 207 |
|
| 208 |
for i in request.body: |
| 209 |
low_conn.send(hex(len(i))[2:].encode('utf-8')) |
| 210 |
low_conn.send(b'\r\n') |
| 211 |
low_conn.send(i) |
| 212 |
low_conn.send(b'\r\n') |
| 213 |
low_conn.send(b'0\r\n\r\n') |
| 214 |
|
| 215 |
r = low_conn.getresponse() |
| 216 |
resp = HTTPResponse.from_httplib(r, |
| 217 |
pool=conn, |
| 218 |
connection=low_conn, |
| 219 |
preload_content=False, |
| 220 |
decode_content=False |
| 221 |
) |
| 222 |
|
| 223 |
except socket.error as sockerr: |
| 224 |
raise ConnectionError(sockerr) |
| 225 |
|
| 226 |
except MaxRetryError as e: |
| 227 |
raise ConnectionError(e) |
| 228 |
|
| 229 |
except (_SSLError, _HTTPError) as e: |
| 230 |
if isinstance(e, _SSLError): |
| 231 |
raise SSLError(e) |
| 232 |
elif isinstance(e, TimeoutError): |
| 233 |
raise Timeout(e) |
| 234 |
else: |
| 235 |
raise |
| 236 |
|
| 237 |
r = self.build_response(request, resp) |
| 238 |
|
| 239 |
if not stream: |
| 240 |
r.content |
| 241 |
|
| 242 |
return r |