Skip to content
Myr

merge 2.0 insto master

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Kenneth Reitz · committed by Kenneth Reitz · parents 23ced52, 12760f2 · Browse files · 22 files+1185 added−204 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

22 files+1185 added−204 removed

  • other:+1185 added−204 removed

22 files+1185 added−204 removed

modified:docs/index.rst+1 added-1 removed
36 unmodified lines
3738Testimonials39------------4041Her Majesty's Government, Amazon, Google, Runscope, Twilio, Mozilla, Heroku, PayPal, NPR, Obama for America, Transifex, Native Instruments, The Washington Post, Twitter, SoundCloud, Kippt, Readability, and Federal US Institutions use Requests internally. It has been downloaded over 3,000,000 times from PyPI.41Her Majesty's Government, Amazon, Google, Twilio, Runscope, Mozilla, Heroku, PayPal, NPR, Obama for America, Transifex, Native Instruments, The Washington Post, Twitter, SoundCloud, Kippt, Readability, and Federal US Institutions use Requests internally. It has been downloaded over 5,000,000 times from PyPI.4243**Armin Ronacher**44 Requests is the perfect example how beautiful an API can be with the45 right level of abstraction.
90 unmodified lines
modified:requests/packages/urllib3/contrib/pyopenssl.py+179 added-8 removed
18 unmodified lines
19Now you can use :mod:`urllib3` as you normally would, and it will support SNI20when the required modules are installed.21'''2223from ndg.httpsclient.ssl_peer_verification import (ServerSSLCertVerification,24 SUBJ_ALT_NAME_SUPPORT)23from ndg.httpsclient.ssl_peer_verification import SUBJ_ALT_NAME_SUPPORT24from ndg.httpsclient.subj_alt_name import SubjectAltName25import OpenSSL.SSL26from pyasn1.codec.der import decoder as der_decoder27from socket import _fileobject28import ssl29from cStringIO import StringIO3031from .. import connectionpool32from .. import util33
64 unmodified lines
9899 return dns_name100101102class fileobject(_fileobject):103104 def read(self, size=-1):105 # Use max, disallow tiny reads in a loop as they are very inefficient.106 # We never leave read() with any leftover data from a new recv() call107 # in our internal buffer.108 rbufsize = max(self._rbufsize, self.default_bufsize)109 # Our use of StringIO rather than lists of string objects returned by110 # recv() minimizes memory usage and fragmentation that occurs when111 # rbufsize is large compared to the typical return value of recv().112 buf = self._rbuf113 buf.seek(0, 2) # seek end114 if size < 0:115 # Read until EOF116 self._rbuf = StringIO() # reset _rbuf. we consume it via buf.117 while True:118 try:119 data = self._sock.recv(rbufsize)120 except OpenSSL.SSL.WantReadError:121 continue122 if not data:123 break124 buf.write(data)125 return buf.getvalue()126 else:127 # Read until size bytes or EOF seen, whichever comes first128 buf_len = buf.tell()129 if buf_len >= size:130 # Already have size bytes in our buffer? Extract and return.131 buf.seek(0)132 rv = buf.read(size)133 self._rbuf = StringIO()134 self._rbuf.write(buf.read())135 return rv136137 self._rbuf = StringIO() # reset _rbuf. we consume it via buf.138 while True:139 left = size - buf_len140 # recv() will malloc the amount of memory given as its141 # parameter even though it often returns much less data142 # than that. The returned data string is short lived143 # as we copy it into a StringIO and free it. This avoids144 # fragmentation issues on many platforms.145 try:146 data = self._sock.recv(left)147 except OpenSSL.SSL.WantReadError:148 continue149 if not data:150 break151 n = len(data)152 if n == size and not buf_len:153 # Shortcut. Avoid buffer data copies when:154 # - We have no data in our buffer.155 # AND156 # - Our call to recv returned exactly the157 # number of bytes we were asked to read.158 return data159 if n == left:160 buf.write(data)161 del data # explicit free162 break163 assert n <= left, "recv(%d) returned %d bytes" % (left, n)164 buf.write(data)165 buf_len += n166 del data # explicit free167 #assert buf_len == buf.tell()168 return buf.getvalue()169170 def readline(self, size=-1):171 buf = self._rbuf172 buf.seek(0, 2) # seek end173 if buf.tell() > 0:174 # check if we already have it in our buffer175 buf.seek(0)176 bline = buf.readline(size)177 if bline.endswith('\n') or len(bline) == size:178 self._rbuf = StringIO()179 self._rbuf.write(buf.read())180 return bline181 del bline182 if size < 0:183 # Read until \n or EOF, whichever comes first184 if self._rbufsize <= 1:185 # Speed up unbuffered case186 buf.seek(0)187 buffers = [buf.read()]188 self._rbuf = StringIO() # reset _rbuf. we consume it via buf.189 data = None190 recv = self._sock.recv191 while True:192 try:193 while data != "\n":194 data = recv(1)195 if not data:196 break197 buffers.append(data)198 except OpenSSL.SSL.WantReadError:199 continue200 break201 return "".join(buffers)202203 buf.seek(0, 2) # seek end204 self._rbuf = StringIO() # reset _rbuf. we consume it via buf.205 while True:206 try:207 data = self._sock.recv(self._rbufsize)208 except OpenSSL.SSL.WantReadError:209 continue210 if not data:211 break212 nl = data.find('\n')213 if nl >= 0:214 nl += 1215 buf.write(data[:nl])216 self._rbuf.write(data[nl:])217 del data218 break219 buf.write(data)220 return buf.getvalue()221 else:222 # Read until size bytes or \n or EOF seen, whichever comes first223 buf.seek(0, 2) # seek end224 buf_len = buf.tell()225 if buf_len >= size:226 buf.seek(0)227 rv = buf.read(size)228 self._rbuf = StringIO()229 self._rbuf.write(buf.read())230 return rv231 self._rbuf = StringIO() # reset _rbuf. we consume it via buf.232 while True:233 try:234 data = self._sock.recv(self._rbufsize)235 except OpenSSL.SSL.WantReadError:236 continue237 if not data:238 break239 left = size - buf_len240 # did we just receive a newline?241 nl = data.find('\n', 0, left)242 if nl >= 0:243 nl += 1244 # save the excess data to _rbuf245 self._rbuf.write(data[nl:])246 if buf_len:247 buf.write(data[:nl])248 break249 else:250 # Shortcut. Avoid data copy through buf when returning251 # a substring of our first recv().252 return data[:nl]253 n = len(data)254 if n == size and not buf_len:255 # Shortcut. Avoid data copy through buf when256 # returning exactly all of our first recv().257 return data258 if n >= left:259 buf.write(data[:left])260 self._rbuf.write(data[left:])261 break262 buf.write(data)263 buf_len += n264 #assert buf_len == buf.tell()265 return buf.getvalue()266267268class WrappedSocket(object):269 '''API-compatibility wrapper for Python OpenSSL's Connection-class.'''270271 def __init__(self, connection, socket):
3 unmodified lines
275 def fileno(self):276 return self.socket.fileno()277278 def makefile(self, mode, bufsize=-1):113 return _fileobject(self.connection, mode, bufsize)279 return fileobject(self.connection, mode, bufsize)280281 def settimeout(self, timeout):282 return self.socket.settimeout(timeout)283
4 unmodified lines
288 return self.connection.shutdown()289290 def getpeercert(self, binary_form=False):291 x509 = self.connection.get_peer_certificate()292293 if not x509:127 raise ssl.SSLError('')294 return x509295296 if binary_form:297 return OpenSSL.crypto.dump_certificate(298 OpenSSL.crypto.FILETYPE_ASN1,
32 unmodified lines
331332 cnx = OpenSSL.SSL.Connection(ctx, sock)333 cnx.set_tlsext_host_name(server_hostname)334 cnx.set_connect_state()335 while True:168 try:169 cnx.do_handshake()170 except OpenSSL.SSL.Error as e:171 raise ssl.SSLError('bad handshake', e)336 try:337 cnx.do_handshake()338 except OpenSSL.SSL.WantReadError:339 continue340 except OpenSSL.SSL.Error as e:341 raise ssl.SSLError('bad handshake', e)342 break343344 return WrappedSocket(cnx, sock)
modified:requests/packages/urllib3/packages/ssl_match_hostname/__init__.py+52 added-15 removed
5 unmodified lines
67class CertificateError(ValueError):8 pass910def _dnsname_to_pat(dn):10def _dnsname_match(dn, hostname, max_wildcards=1):11 """Matching according to RFC 6125, section 6.4.31213 http://tools.ietf.org/html/rfc6125#section-6.4.314 """15 pats = []12 for frag in dn.split(r'.'):13 if frag == '*':14 # When '*' is a fragment by itself, it matches a non-empty dotless15 # fragment.16 pats.append('[^.]+')17 else:18 # Otherwise, '*' matches any dotless fragment.19 frag = re.escape(frag)20 pats.append(frag.replace(r'\*', '[^.]*'))21 return re.compile(r'\A' + r'\.'.join(pats) + r'\Z', re.IGNORECASE)16 if not dn:17 return False1819 parts = dn.split(r'.')20 leftmost = parts[0]2122 wildcards = leftmost.count('*')23 if wildcards > max_wildcards:24 # Issue #17980: avoid denials of service by refusing more25 # than one wildcard per fragment. A survery of established26 # policy among SSL implementations showed it to be a27 # reasonable choice.28 raise CertificateError(29 "too many wildcards in certificate DNS name: " + repr(dn))3031 # speed up common case w/o wildcards32 if not wildcards:33 return dn.lower() == hostname.lower()3435 # RFC 6125, section 6.4.3, subitem 1.36 # The client SHOULD NOT attempt to match a presented identifier in which37 # the wildcard character comprises a label other than the left-most label.38 if leftmost == '*':39 # When '*' is a fragment by itself, it matches a non-empty dotless40 # fragment.41 pats.append('[^.]+')42 elif leftmost.startswith('xn--') or hostname.startswith('xn--'):43 # RFC 6125, section 6.4.3, subitem 3.44 # The client SHOULD NOT attempt to match a presented identifier45 # where the wildcard character is embedded within an A-label or46 # U-label of an internationalized domain name.47 pats.append(re.escape(leftmost))48 else:49 # Otherwise, '*' matches any dotless string, e.g. www*50 pats.append(re.escape(leftmost).replace(r'\*', '[^.]*'))5152 # add the remaining fragments, ignore any wildcards53 for frag in parts[1:]:54 pats.append(re.escape(frag))5556 pat = re.compile(r'\A' + r'\.'.join(pats) + r'\Z', re.IGNORECASE)57 return pat.match(hostname)585960def match_hostname(cert, hostname):61 """Verify that *cert* (in decoded format as returned by25 SSLSocket.getpeercert()) matches the *hostname*. RFC 2818 rules26 are mostly followed, but IP addresses are not accepted for *hostname*.62 SSLSocket.getpeercert()) matches the *hostname*. RFC 2818 and RFC 612563 rules are followed, but IP addresses are not accepted for *hostname*.6465 CertificateError is raised on failure. On success, the function66 returns nothing.67 """
2 unmodified lines
70 dnsnames = []71 san = cert.get('subjectAltName', ())72 for key, value in san:73 if key == 'DNS':37 if _dnsname_to_pat(value).match(hostname):74 if _dnsname_match(value, hostname):75 return76 dnsnames.append(value)77 if not dnsnames:78 # The subject is only checked when there is no dNSName entry
2 unmodified lines
81 for key, value in sub:82 # XXX according to RFC 2818, the most specific Common Name83 # must be used.84 if key == 'commonName':48 if _dnsname_to_pat(value).match(hostname):85 if _dnsname_match(value, hostname):86 return87 dnsnames.append(value)88 if len(dnsnames) > 1:89 raise CertificateError("hostname %r "
9 unmodified lines
modified:requests/packages/urllib3/__init__.py+1 added-1 removed
21 unmodified lines
22from . import exceptions23from .filepost import encode_multipart_formdata24from .poolmanager import PoolManager, ProxyManager, proxy_from_url25from .response import HTTPResponse26from .util import make_headers, get_host26from .util import make_headers, get_host, Timeout272829# Set default logging handler to avoid "No handler found" warnings.30import logging
28 unmodified lines
modified:requests/packages/urllib3/connectionpool.py+209 added-62 removed
2 unmodified lines
3#4# This module is part of urllib3 and is released under5# the MIT License: http://www.opensource.org/licenses/mit-license.php67import logging8import socket7import errno8import logging910from socket import error as SocketError, timeout as SocketTimeout12from .util import resolve_cert_reqs, resolve_ssl_version, assert_fingerprint11import socket1213try: # Python 314 from http.client import HTTPConnection, HTTPException15 from http.client import HTTP_PORT, HTTPS_PORT
4 unmodified lines
20try: # Python 321 from queue import LifoQueue, Empty, Full22except ImportError:23 from Queue import LifoQueue, Empty, Full24 import Queue as _ # Platform-specific: Windows252627try: # Compiled with SSL?28 HTTPSConnection = object
14 unmodified lines
43except (ImportError, AttributeError): # Platform-specific: No SSL.44 pass454647from .request import RequestMethods48from .response import HTTPResponse49from .util import get_host, is_connection_dropped, ssl_wrap_socket47from .exceptions import (48 ClosedPoolError,49 ConnectTimeoutError,50 EmptyPoolError,51 HostChangedError,52 MaxRetryError,53 SSLError,56 TimeoutError,54 ReadTimeoutError,55 ProxyError,56)5859from .packages.ssl_match_hostname import match_hostname, CertificateError57from .packages.ssl_match_hostname import CertificateError, match_hostname58from .packages import six59from .request import RequestMethods60from .response import HTTPResponse61from .util import (62 assert_fingerprint,63 get_host,64 is_connection_dropped,65 resolve_cert_reqs,66 resolve_ssl_version,67 ssl_wrap_socket,68 Timeout,69)706271xrange = six.moves.xrange7273log = logging.getLogger(__name__)74
28 unmodified lines
103 self.assert_fingerprint = assert_fingerprint104105 def connect(self):106 # Add certificate verification99 sock = socket.create_connection((self.host, self.port), self.timeout)107 try:108 sock = socket.create_connection(109 address=(self.host, self.port),110 timeout=self.timeout)111 except SocketTimeout:112 raise ConnectTimeoutError(113 self, "Connection to %s timed out. (connect timeout=%s)" %114 (self.host, self.timeout))115116 resolved_cert_reqs = resolve_cert_reqs(self.cert_reqs)117 resolved_ssl_version = resolve_ssl_version(self.ssl_version)118119 if self._tunnel_host:120 self.sock = sock121 # Calls self._set_hostport(), so self.host is122 # self._tunnel_host below.123 self._tunnel()124125 # Wrap socket using verification with the root certs in126 # trusted_root_certs127 self.sock = ssl_wrap_socket(sock, self.key_file, self.cert_file,128 cert_reqs=resolved_cert_reqs,
8 unmodified lines
137 elif self.assert_hostname is not False:138 match_hostname(self.sock.getpeercert(),139 self.assert_hostname or self.host)140141142## Pool objects143144class ConnectionPool(object):145 """
4 unmodified lines
150 scheme = None151 QueueCls = LifoQueue152153 def __init__(self, host, port=None):154 # httplib doesn't like it when we include brackets in ipv6 addresses155 host = host.strip('[]')156157 self.host = host158 self.port = port159160 def __str__(self):161 return '%s(host=%r, port=%r)' % (type(self).__name__,162 self.host, self.port)163164# This is taken from http://hg.python.org/cpython/file/7aaba721ebc0/Lib/socket.py#l252165_blocking_errnos = set([errno.EAGAIN, errno.EWOULDBLOCK])166167class HTTPConnectionPool(ConnectionPool, RequestMethods):168 """169 Thread-safe connection pool for one host.
10 unmodified lines
180 Causes BadStatusLine to be raised if the status line can't be parsed181 as a valid HTTP/1.0 or 1.1 status line, passed into182 :class:`httplib.HTTPConnection`.183184 .. note::185 Only works in Python 2. This parameter is ignored in Python 3.186187 :param timeout:158 Socket timeout in seconds for each individual connection, can be159 a float. None disables timeout.188 Socket timeout in seconds for each individual connection. This can189 be a float or integer, which sets the timeout for the HTTP request,190 or an instance of :class:`urllib3.util.Timeout` which gives you more191 fine-grained control over request timeouts. After the constructor has192 been parsed, this is always a `urllib3.util.Timeout` object.193194 :param maxsize:195 Number of connections to save that can be reused. More than 1 is useful196 in multithreaded situations. If ``block`` is set to false, more
9 unmodified lines
206207 :param headers:208 Headers to include with all requests, unless other headers are given209 explicitly.210211 :param _proxy:212 Parsed proxy URL, should not be used directly, instead, see213 :class:`urllib3.connectionpool.ProxyManager`"214215 :param _proxy_headers:216 A dictionary with proxy headers, should not be used directly,217 instead, see :class:`urllib3.connectionpool.ProxyManager`"218 """219220 scheme = 'http'221181 def __init__(self, host, port=None, strict=False, timeout=None, maxsize=1,182 block=False, headers=None):222 def __init__(self, host, port=None, strict=False,223 timeout=Timeout.DEFAULT_TIMEOUT, maxsize=1, block=False,224 headers=None, _proxy=None, _proxy_headers=None):225 ConnectionPool.__init__(self, host, port)226 RequestMethods.__init__(self, headers)227228 self.strict = strict229230 # This is for backwards compatibility and can be removed once a timeout231 # can only be set to a Timeout object232 if not isinstance(timeout, Timeout):233 timeout = Timeout.from_float(timeout)234235 self.timeout = timeout236237 self.pool = self.QueueCls(maxsize)238 self.block = block239240 self.proxy = _proxy241 self.proxy_headers = _proxy_headers or {}242243 # Fill the queue up so that doing get() on it will block properly244 for _ in xrange(maxsize):245 self.pool.put(None)246
7 unmodified lines
254 """255 self.num_connections += 1256 log.info("Starting new HTTP connection (%d): %s" %257 (self.num_connections, self.host))206 return HTTPConnection(host=self.host,207 port=self.port,208 strict=self.strict)258 extra_params = {}259 if not six.PY3: # Python 2260 extra_params['strict'] = self.strict261262 return HTTPConnection(host=self.host, port=self.port,263 timeout=self.timeout.connect_timeout,264 **extra_params)265266267 def _get_conn(self, timeout=None):268 """269 Get a connection. Will return a pooled connection if one is available.270
51 unmodified lines
322 log.warning("HttpConnectionPool is full, discarding connection: %s"323 % self.host)324325 # Connection never got put back into the pool, close it.326 if conn:269 conn.close()327 conn.close()328329 def _get_timeout(self, timeout):330 """ Helper that always returns a :class:`urllib3.util.Timeout` """331 if timeout is _Default:332 return self.timeout.clone()333334 if isinstance(timeout, Timeout):335 return timeout.clone()336 else:337 # User passed us an int/float. This is for backwards compatibility,338 # can be removed later339 return Timeout.from_float(timeout)340341 def _make_request(self, conn, method, url, timeout=_Default,342 **httplib_request_kw):343 """344 Perform a request on a given httplib connection object taken from our345 pool.346347 :param conn:348 a connection from one of our connection pools349350 :param timeout:351 Socket timeout in seconds for the request. This can be a352 float or integer, which will set the same timeout value for353 the socket connect and the socket read, or an instance of354 :class:`urllib3.util.Timeout`, which gives you more fine-grained355 control over your timeouts.356 """357 self.num_requests += 1358279 if timeout is _Default:280 timeout = self.timeout359 timeout_obj = self._get_timeout(timeout)360282 conn.timeout = timeout # This only does anything in Py26+283 conn.request(method, url, **httplib_request_kw)361 try:362 timeout_obj.start_connect()363 conn.timeout = timeout_obj.connect_timeout364 # conn.request() calls httplib.*.request, not the method in365 # request.py. It also calls makefile (recv) on the socket366 conn.request(method, url, **httplib_request_kw)367 except SocketTimeout:368 raise ConnectTimeoutError(369 self, "Connection to %s timed out. (connect timeout=%s)" %370 (self.host, timeout_obj.connect_timeout))371285 # Set timeout286 sock = getattr(conn, 'sock', False) # AppEngine doesn't have sock attr.287 if sock:288 sock.settimeout(timeout)372 # Reset the timeout for the recv() on the socket373 read_timeout = timeout_obj.read_timeout374 log.debug("Setting read timeout to %s" % read_timeout)375 # App Engine doesn't have a sock attr376 if hasattr(conn, 'sock') and \377 read_timeout is not None and \378 read_timeout is not Timeout.DEFAULT_TIMEOUT:379 # In Python 3 socket.py will catch EAGAIN and return None when you380 # try and read into the file pointer created by http.client, which381 # instead raises a BadStatusLine exception. Instead of catching382 # the exception and assuming all BadStatusLine exceptions are read383 # timeouts, check for a zero timeout before making the request.384 if read_timeout == 0:385 raise ReadTimeoutError(386 self, url,387 "Read timed out. (read timeout=%s)" % read_timeout)388 conn.sock.settimeout(read_timeout)389390 # Receive the response from the server391 try:290 try: # Python 2.7+, use buffering of HTTP responses291 httplib_response = conn.getresponse(buffering=True)292 except TypeError: # Python 2.6 and older293 httplib_response = conn.getresponse()392 try: # Python 2.7+, use buffering of HTTP responses393 httplib_response = conn.getresponse(buffering=True)394 except TypeError: # Python 2.6 and older395 httplib_response = conn.getresponse()396 except SocketTimeout:397 raise ReadTimeoutError(398 self, url, "Read timed out. (read timeout=%s)" % read_timeout)399400 except SocketError as e: # Platform-specific: Python 2401 # See the above comment about EAGAIN in Python 3. In Python 2 we402 # have to specifically catch it and throw the timeout error403 if e.errno in _blocking_errnos:404 raise ReadTimeoutError(405 self, url,406 "Read timed out. (read timeout=%s)" % read_timeout)407 raise408409410 # AppEngine doesn't have a version attr.411 http_version = getattr(conn, '_http_vsn_str', 'HTTP/?')412 log.debug("\"%s %s %s\" %s %s" % (method, url, http_version,413 httplib_response.status,
70 unmodified lines
484 Number of retries to allow before raising a MaxRetryError exception.485486 :param redirect:487 If True, automatically handle redirects (status codes 301, 302,373 303, 307). Each redirect counts as a retry.488 303, 307, 308). Each redirect counts as a retry.489490 :param assert_same_host:491 If ``True``, will make sure that the host of the pool requests is492 consistent else will raise HostChangedError. When False, you can493 use the pool on an HTTP proxy and request foreign hosts.494495 :param timeout:381 If specified, overrides the default timeout for this one request.382 It may be a float (in seconds).496 If specified, overrides the default timeout for this one497 request. It may be a float (in seconds) or an instance of498 :class:`urllib3.util.Timeout`.499500 :param pool_timeout:501 If set and the pool is set to block=True, then this method will502 block for ``pool_timeout`` seconds and raise EmptyPoolError if no
18 unmodified lines
521522 if retries < 0:523 raise MaxRetryError(self, url)524409 if timeout is _Default:410 timeout = self.timeout411525 if release_conn is None:526 release_conn = response_kw.get('preload_content', True)527528 # Check host
27 unmodified lines
556 # The connection will be put back into the pool when557 # ``response.release_conn()`` is called (implicitly by558 # ``response.read()``)559447 except Empty as e:560 except Empty:561 # Timed out by queue449 raise TimeoutError(self, url,450 "Request timed out. (pool_timeout=%s)" %451 pool_timeout)562 raise ReadTimeoutError(563 self, url, "Read timed out, no pool connections are available.")564453 except SocketTimeout as e:565 except SocketTimeout:566 # Timed out by socket455 raise TimeoutError(self, url,456 "Request timed out. (timeout=%s)" %457 timeout)567 raise ReadTimeoutError(self, url, "Read timed out.")568569 except BaseSSLError as e:570 # SSL certificate error571 if 'timed out' in str(e) or \572 'did not complete (read)' in str(e): # Platform-specific: Python 2.6573 raise ReadTimeoutError(self, url, "Read timed out.")574 raise SSLError(e)575576 except CertificateError as e:577 # Name mismatch578 raise SSLError(e)579580 except (HTTPException, SocketError) as e:581 if isinstance(e, SocketError) and self.proxy is not None:582 raise ProxyError('Cannot connect to proxy. '583 'Socket error: %s.' % e)584585 # Connection broken, discard. It will be replaced next _get_conn().586 conn = None587 # This is necessary so we can access e below588 err = e
53 unmodified lines
642643 def __init__(self, host, port=None,644 strict=False, timeout=None, maxsize=1,645 block=False, headers=None,646 _proxy=None, _proxy_headers=None,647 key_file=None, cert_file=None, cert_reqs=None,648 ca_certs=None, ssl_version=None,649 assert_hostname=None, assert_fingerprint=None):650533 HTTPConnectionPool.__init__(self, host, port,534 strict, timeout, maxsize,535 block, headers)651 HTTPConnectionPool.__init__(self, host, port, strict, timeout, maxsize,652 block, headers, _proxy, _proxy_headers)653 self.key_file = key_file654 self.cert_file = cert_file655 self.cert_reqs = cert_reqs656 self.ca_certs = ca_certs657 self.ssl_version = ssl_version658 self.assert_hostname = assert_hostname659 self.assert_fingerprint = assert_fingerprint660661 def _prepare_conn(self, connection):662 """663 Prepare the ``connection`` for :meth:`urllib3.util.ssl_wrap_socket`664 and establish the tunnel if proxy is used.665 """666667 if isinstance(connection, VerifiedHTTPSConnection):668 connection.set_cert(key_file=self.key_file,669 cert_file=self.cert_file,670 cert_reqs=self.cert_reqs,671 ca_certs=self.ca_certs,672 assert_hostname=self.assert_hostname,673 assert_fingerprint=self.assert_fingerprint)674 connection.ssl_version = self.ssl_version675676 if self.proxy is not None:677 # Python 2.7+678 try:679 set_tunnel = connection.set_tunnel680 except AttributeError: # Platform-specific: Python 2.6681 set_tunnel = connection._set_tunnel682 set_tunnel(self.host, self.port, self.proxy_headers)683 # Establish tunnel connection early, because otherwise httplib684 # would improperly set Host: header to proxy's IP:port.685 connection.connect()686687 return connection688689 def _new_conn(self):690 """691 Return a fresh :class:`httplib.HTTPSConnection`.692 """693 self.num_connections += 1694 log.info("Starting new HTTPS connection (%d): %s"695 % (self.num_connections, self.host))696697 actual_host = self.host698 actual_port = self.port699 if self.proxy is not None:700 actual_host = self.proxy.host701 actual_port = self.proxy.port702703 if not ssl: # Platform-specific: Python compiled without +ssl704 if not HTTPSConnection or HTTPSConnection is object:705 raise SSLError("Can't connect to HTTPS URL because the SSL "706 "module is not available.")707 connection_class = HTTPSConnection708 else:709 connection_class = VerifiedHTTPSConnection710557 return HTTPSConnection(host=self.host,558 port=self.port,559 strict=self.strict)711 extra_params = {}712 if not six.PY3: # Python 2713 extra_params['strict'] = self.strict714 connection = connection_class(host=actual_host, port=actual_port,715 timeout=self.timeout.connect_timeout,716 **extra_params)717561 connection = VerifiedHTTPSConnection(host=self.host,562 port=self.port,563 strict=self.strict)564 connection.set_cert(key_file=self.key_file, cert_file=self.cert_file,565 cert_reqs=self.cert_reqs, ca_certs=self.ca_certs,566 assert_hostname=self.assert_hostname,567 assert_fingerprint=self.assert_fingerprint)718 return self._prepare_conn(connection)719569 connection.ssl_version = self.ssl_version720571 return connection572573721def connection_from_url(url, **kw):722 """723 Given a url, return an :class:`.ConnectionPool` instance of its host.724
21 unmodified lines
modified:requests/packages/urllib3/exceptions.py+28 added-2 removed
37 unmodified lines
38 "Raised when SSL certificate fails in an HTTPS connection."39 pass404142class ProxyError(HTTPError):43 "Raised when the connection to a proxy fails."44 pass454647class DecodeError(HTTPError):48 "Raised when automatic decoding based on Content-Type fails."49 pass50
23 unmodified lines
74 RequestError.__init__(self, pool, url, message)75 self.retries = retries767773class TimeoutError(RequestError):74 "Raised when a socket timeout occurs."78class TimeoutStateError(HTTPError):79 """ Raised when passing an invalid state to a timeout """80 pass818283class TimeoutError(HTTPError):84 """ Raised when a socket timeout error occurs.8586 Catching this error will catch both :exc:`ReadTimeoutErrors87 <ReadTimeoutError>` and :exc:`ConnectTimeoutErrors <ConnectTimeoutError>`.88 """89 pass909192class ReadTimeoutError(TimeoutError, RequestError):93 "Raised when a socket timeout occurs while receiving data from a server"94 pass959697# This timeout error does not have a URL attached and needs to inherit from the98# base HTTPError99class ConnectTimeoutError(TimeoutError):100 "Raised when a socket timeout occurs while connecting to a server"101 pass102103104class EmptyPoolError(PoolError):105 "Raised when a pool runs out of connections and no more are allowed."106 pass107
14 unmodified lines
added:requests/packages/urllib3/fields.py+177 added
1# urllib3/fields.py2# Copyright 2008-2013 Andrey Petrov and contributors (see CONTRIBUTORS.txt)3#4# This module is part of urllib3 and is released under5# the MIT License: http://www.opensource.org/licenses/mit-license.php67import email.utils8import mimetypes910from .packages import six111213def guess_content_type(filename, default='application/octet-stream'):14 """15 Guess the "Content-Type" of a file.1617 :param filename:18 The filename to guess the "Content-Type" of using :mod:`mimetimes`.19 :param default:20 If no "Content-Type" can be guessed, default to `default`.21 """22 if filename:23 return mimetypes.guess_type(filename)[0] or default24 return default252627def format_header_param(name, value):28 """29 Helper function to format and quote a single header parameter.3031 Particularly useful for header parameters which might contain32 non-ASCII values, like file names. This follows RFC 2231, as33 suggested by RFC 2388 Section 4.4.3435 :param name:36 The name of the parameter, a string expected to be ASCII only.37 :param value:38 The value of the parameter, provided as a unicode string.39 """40 if not any(ch in value for ch in '"\\\r\n'):41 result = '%s="%s"' % (name, value)42 try:43 result.encode('ascii')44 except UnicodeEncodeError:45 pass46 else:47 return result48 if not six.PY3: # Python 2:49 value = value.encode('utf-8')50 value = email.utils.encode_rfc2231(value, 'utf-8')51 value = '%s*=%s' % (name, value)52 return value535455class RequestField(object):56 """57 A data container for request body parameters.5859 :param name:60 The name of this request field.61 :param data:62 The data/value body.63 :param filename:64 An optional filename of the request field.65 :param headers:66 An optional dict-like object of headers to initially use for the field.67 """68 def __init__(self, name, data, filename=None, headers=None):69 self._name = name70 self._filename = filename71 self.data = data72 self.headers = {}73 if headers:74 self.headers = dict(headers)7576 @classmethod77 def from_tuples(cls, fieldname, value):78 """79 A :class:`~urllib3.fields.RequestField` factory from old-style tuple parameters.8081 Supports constructing :class:`~urllib3.fields.RequestField` from parameter82 of key/value strings AND key/filetuple. A filetuple is a (filename, data, MIME type)83 tuple where the MIME type is optional. For example: ::8485 'foo': 'bar',86 'fakefile': ('foofile.txt', 'contents of foofile'),87 'realfile': ('barfile.txt', open('realfile').read()),88 'typedfile': ('bazfile.bin', open('bazfile').read(), 'image/jpeg'),89 'nonamefile': 'contents of nonamefile field',9091 Field names and filenames must be unicode.92 """93 if isinstance(value, tuple):94 if len(value) == 3:95 filename, data, content_type = value96 else:97 filename, data = value98 content_type = guess_content_type(filename)99 else:100 filename = None101 content_type = None102 data = value103104 request_param = cls(fieldname, data, filename=filename)105 request_param.make_multipart(content_type=content_type)106107 return request_param108109 def _render_part(self, name, value):110 """111 Overridable helper function to format a single header parameter.112113 :param name:114 The name of the parameter, a string expected to be ASCII only.115 :param value:116 The value of the parameter, provided as a unicode string.117 """118 return format_header_param(name, value)119120 def _render_parts(self, header_parts):121 """122 Helper function to format and quote a single header.123124 Useful for single headers that are composed of multiple items. E.g.,125 'Content-Disposition' fields.126127 :param header_parts:128 A sequence of (k, v) typles or a :class:`dict` of (k, v) to format as129 `k1="v1"; k2="v2"; ...`.130 """131 parts = []132 iterable = header_parts133 if isinstance(header_parts, dict):134 iterable = header_parts.items()135136 for name, value in iterable:137 if value:138 parts.append(self._render_part(name, value))139140 return '; '.join(parts)141142 def render_headers(self):143 """144 Renders the headers for this request field.145 """146 lines = []147148 sort_keys = ['Content-Disposition', 'Content-Type', 'Content-Location']149 for sort_key in sort_keys:150 if self.headers.get(sort_key, False):151 lines.append('%s: %s' % (sort_key, self.headers[sort_key]))152153 for header_name, header_value in self.headers.items():154 if header_name not in sort_keys:155 if header_value:156 lines.append('%s: %s' % (header_name, header_value))157158 lines.append('\r\n')159 return '\r\n'.join(lines)160161 def make_multipart(self, content_disposition=None, content_type=None, content_location=None):162 """163 Makes this request field into a multipart request field.164165 This method overrides "Content-Disposition", "Content-Type" and166 "Content-Location" headers to the request parameter.167168 :param content_type:169 The 'Content-Type' of the request body.170 :param content_location:171 The 'Content-Location' of the request body.172173 """174 self.headers['Content-Disposition'] = content_disposition or 'form-data'175 self.headers['Content-Disposition'] += '; '.join(['', self._render_parts((('name', self._name), ('filename', self._filename)))])176 self.headers['Content-Type'] = content_type177 self.headers['Content-Location'] = content_location
modified:requests/packages/urllib3/filepost.py+30 added-27 removed
10 unmodified lines
11from io import BytesIO1213from .packages import six14from .packages.six import b15from .fields import RequestField1617writer = codecs.lookup('utf-8')[3]1819
3 unmodified lines
23 """24 return uuid4().hex252626def get_content_type(filename):27 return mimetypes.guess_type(filename)[0] or 'application/octet-stream'27def iter_field_objects(fields):28 """29 Iterate over fields.3031 Supports list of (k, v) tuples and dicts, and lists of32 :class:`~urllib3.fields.RequestField`.3334 """35 if isinstance(fields, dict):36 i = six.iteritems(fields)37 else:38 i = iter(fields)3940 for field in i:41 if isinstance(field, RequestField):42 yield field43 else:44 yield RequestField.from_tuples(*field)454647def iter_fields(fields):48 """49 Iterate over fields.5051 .. deprecated ::5253 The addition of `~urllib3.fields.RequestField` makes this function54 obsolete. Instead, use :func:`iter_field_objects`, which returns55 `~urllib3.fields.RequestField` objects, instead.5657 Supports list of (k, v) tuples and dicts.5859 """60 if isinstance(fields, dict):61 return ((k, v) for k, v in six.iteritems(fields))62
4 unmodified lines
67 """68 Encode a dictionary of ``fields`` using the multipart/form-data MIME format.6970 :param fields:47 Dictionary of fields or list of (key, value) or (key, value, MIME type)48 field tuples. The key is treated as the field name, and the value as49 the body of the form-data bytes. If the value is a tuple of two50 elements, then the first element is treated as the filename of the51 form-data section and a suitable MIME type is guessed based on the52 filename. If the value is a tuple of three elements, then the third53 element is treated as an explicit MIME type of the form-data section.71 Dictionary of fields or list of (key, :class:`~urllib3.fields.RequestField`).7255 Field names and filenames must be unicode.5673 :param boundary:74 If not specified, then a random boundary will be generated using75 :func:`mimetools.choose_boundary`.76 """77 body = BytesIO()78 if boundary is None:79 boundary = choose_boundary()8065 for fieldname, value in iter_fields(fields):81 for field in iter_field_objects(fields):82 body.write(b('--%s\r\n' % (boundary)))8368 if isinstance(value, tuple):69 if len(value) == 3:70 filename, data, content_type = value71 else:72 filename, data = value73 content_type = get_content_type(filename)74 writer(body).write('Content-Disposition: form-data; name="%s"; '75 'filename="%s"\r\n' % (fieldname, filename))76 body.write(b('Content-Type: %s\r\n\r\n' %77 (content_type,)))78 else:79 data = value80 writer(body).write('Content-Disposition: form-data; name="%s"\r\n'81 % (fieldname))82 body.write(b'\r\n')84 writer(body).write(field.render_headers())85 data = field.data8687 if isinstance(data, int):88 data = str(data) # Backwards compatibility89
12 unmodified lines
modified:requests/packages/urllib3/poolmanager.py+81 added-24 removed
11 unmodified lines
12 from urlparse import urljoin1314from ._collections import RecentlyUsedContainer15from .connectionpool import HTTPConnectionPool, HTTPSConnectionPool16from .connectionpool import connection_from_url, port_by_scheme16from .connectionpool import port_by_scheme17from .request import RequestMethods18from .util import parse_url1920
38 unmodified lines
59 26061 """6263 proxy = None6465 def __init__(self, num_pools=10, headers=None, **connection_pool_kw):66 RequestMethods.__init__(self, headers)67 self.connection_pool_kw = connection_pool_kw68 self.pools = RecentlyUsedContainer(num_pools,
31 unmodified lines
100101 If ``port`` isn't given, it will be derived from the ``scheme`` using102 ``urllib3.connectionpool.port_by_scheme``.103 """104105 scheme = scheme or 'http'106107 port = port or port_by_scheme.get(scheme, 80)108109 pool_key = (scheme, host, port)110111 with self.pools.lock:108 # If the scheme, host, or port doesn't match existing open connections,109 # open a new ConnectionPool.110 pool = self.pools.get(pool_key)111 if pool:112 return pool112 # If the scheme, host, or port doesn't match existing open113 # connections, open a new ConnectionPool.114 pool = self.pools.get(pool_key)115 if pool:116 return pool117114 # Make a fresh ConnectionPool of the desired type115 pool = self._new_pool(scheme, host, port)116 self.pools[pool_key] = pool118 # Make a fresh ConnectionPool of the desired type119 pool = self._new_pool(scheme, host, port)120 self.pools[pool_key] = pool121 return pool122123 def connection_from_url(self, url):124 """
23 unmodified lines
148 kw['redirect'] = False149 if 'headers' not in kw:150 kw['headers'] = self.headers151152 if self.proxy is not None and u.scheme == "http":153 response = conn.urlopen(method, url, **kw)154 else:148 response = conn.urlopen(method, u.request_uri, **kw)155 response = conn.urlopen(method, u.request_uri, **kw)156157 redirect_location = redirect and response.get_redirect_location()158 if not redirect_location:159 return response
10 unmodified lines
170 kw['redirect'] = redirect171 return self.urlopen(method, redirect_location, **kw)172173167class ProxyManager(RequestMethods):174class ProxyManager(PoolManager):175 """169 Given a ConnectionPool to a proxy, the ProxyManager's ``urlopen`` method170 will make requests to any url through the defined proxy. The ProxyManager171 class will automatically set the 'Host' header if it is not provided.176 Behaves just like :class:`PoolManager`, but sends all requests through177 the defined proxy, using the CONNECT method for HTTPS URLs.178179 :param poxy_url:180 The URL of the proxy to be used.181182 :param proxy_headers:183 A dictionary contaning headers that will be sent to the proxy. In case184 of HTTP they are being sent with each request, while in the185 HTTPS/CONNECT case they are sent only once. Could be used for proxy186 authentication.187188 Example:189 >>> proxy = urllib3.ProxyManager('http://localhost:3128/')190 >>> r1 = proxy.request('GET', 'http://google.com/')191 >>> r2 = proxy.request('GET', 'http://httpbin.org/')192 >>> len(proxy.pools)193 1194 >>> r3 = proxy.request('GET', 'https://httpbin.org/')195 >>> r4 = proxy.request('GET', 'https://twitter.com/')196 >>> len(proxy.pools)197 3198199 """200174 def __init__(self, proxy_pool):175 self.proxy_pool = proxy_pool201 def __init__(self, proxy_url, num_pools=10, headers=None,202 proxy_headers=None, **connection_pool_kw):203204 if isinstance(proxy_url, HTTPConnectionPool):205 proxy_url = '%s://%s:%i' % (proxy_url.scheme, proxy_url.host,206 proxy_url.port)207 proxy = parse_url(proxy_url)208 if not proxy.port:209 port = port_by_scheme.get(proxy.scheme, 80)210 proxy = proxy._replace(port=port)211 self.proxy = proxy212 self.proxy_headers = proxy_headers or {}213 assert self.proxy.scheme in ("http", "https"), \214 'Not supported proxy scheme %s' % self.proxy.scheme215 connection_pool_kw['_proxy'] = self.proxy216 connection_pool_kw['_proxy_headers'] = self.proxy_headers217 super(ProxyManager, self).__init__(218 num_pools, headers, **connection_pool_kw)219220 def connection_from_host(self, host, port=None, scheme='http'):221 if scheme == "https":222 return super(ProxyManager, self).connection_from_host(223 host, port, scheme)224225 return super(ProxyManager, self).connection_from_host(226 self.proxy.host, self.proxy.port, self.proxy.scheme)227228 def _set_proxy_headers(self, url, headers=None):229 """230 Sets headers needed by proxies: specifically, the Accept and Host231 headers. Only sets headers not provided by the user.
5 unmodified lines
237 headers_['Host'] = netloc238239 if headers:240 headers_.update(headers)190241 return headers_242193 def urlopen(self, method, url, **kw):243 def urlopen(self, method, url, redirect=True, **kw):244 "Same as HTTP(S)ConnectionPool.urlopen, ``url`` must be absolute."195 kw['assert_same_host'] = False196 kw['headers'] = self._set_proxy_headers(url, headers=kw.get('headers'))197 return self.proxy_pool.urlopen(method, url, **kw)245 u = parse_url(url)246247 if u.scheme == "http":248 # It's too late to set proxy headers on per-request basis for249 # tunnelled HTTPS connections, should use250 # constructor's proxy_headers instead.251 kw['headers'] = self._set_proxy_headers(url, kw.get('headers',252 self.headers))253 kw['headers'].update(self.proxy_headers)254200def proxy_from_url(url, **pool_kw):201 proxy_pool = connection_from_url(url, **pool_kw)202 return ProxyManager(proxy_pool)255 return super(ProxyManager, self).urlopen(method, url, redirect, **kw)256257258def proxy_from_url(url, **kw):259 return ProxyManager(proxy_url=url, **kw)
modified:requests/packages/urllib3/response.py+3 added-2 removed
72 unmodified lines
73 otherwise unused.74 """7576 CONTENT_DECODERS = ['gzip', 'deflate']77 REDIRECT_STATUSES = [301, 302, 303, 307, 308]7879 def __init__(self, body='', headers=None, status=0, version=0, reason=None,80 strict=0, preload_content=True, decode_content=True,81 original_response=None, pool=None, connection=None):
25 unmodified lines
107 :returns: Truthy redirect location string if we got a redirect status108 code and valid location. ``None`` if redirect status and no109 location. ``False`` if not a redirect status code.110 """110 if self.status in [301, 302, 303, 307]:111 if self.status in self.REDIRECT_STATUSES:112 return self.headers.get('location')113114 return False115
75 unmodified lines
191 "Received response with content-encoding: %s, but "192 "failed to decode it." % content_encoding,193 e)194194 if flush_decoder and self._decoder:195 if flush_decoder and decode_content and self._decoder:196 buf = self._decoder.decompress(binary_type())197 data += buf + self._decoder.flush()198199 if cache_content:
102 unmodified lines
modified:requests/packages/urllib3/util.py+230 added-3 removed
4 unmodified lines
5# the MIT License: http://www.opensource.org/licenses/mit-license.php678from base64 import b64encode9from binascii import hexlify, unhexlify10from collections import namedtuple10from socket import error as SocketError11from hashlib import md5, sha112from binascii import hexlify, unhexlify12from socket import error as SocketError, _GLOBAL_DEFAULT_TIMEOUT13import time1415try:16 from select import poll, POLLIN17except ImportError: # `poll` doesn't exist on OSX and other platforms
14 unmodified lines
32except ImportError:33 pass3435from .packages import six35from .exceptions import LocationParseError, SSLError36from .exceptions import LocationParseError, SSLError, TimeoutStateError373839_Default = object()40# The default timeout to use for socket connections. This is the attribute used41# by httplib to define the default timeout424344def current_time():45 """46 Retrieve the current time, this function is mocked out in unit testing.47 """48 return time.time()495051class Timeout(object):52 """53 Utility object for storing timeout values.5455 Example usage:5657 .. code-block:: python5859 timeout = urllib3.util.Timeout(connect=2.0, read=7.0)60 pool = HTTPConnectionPool('www.google.com', 80, timeout=timeout)61 pool.request(...) # Etc, etc6263 :param connect:64 The maximum amount of time to wait for a connection attempt to a server65 to succeed. Omitting the parameter will default the connect timeout to66 the system default, probably `the global default timeout in socket.py67 <http://hg.python.org/cpython/file/603b4d593758/Lib/socket.py#l535>`_.68 None will set an infinite timeout for connection attempts.6970 :type connect: integer, float, or None7172 :param read:73 The maximum amount of time to wait between consecutive74 read operations for a response from the server. Omitting75 the parameter will default the read timeout to the system76 default, probably `the global default timeout in socket.py77 <http://hg.python.org/cpython/file/603b4d593758/Lib/socket.py#l535>`_.78 None will set an infinite timeout.7980 :type read: integer, float, or None8182 :param total:83 The maximum amount of time to wait for an HTTP request to connect and84 return. This combines the connect and read timeouts into one. In the85 event that both a connect timeout and a total are specified, or a read86 timeout and a total are specified, the shorter timeout will be applied.8788 Defaults to None.899091 :type total: integer, float, or None9293 .. note::9495 Many factors can affect the total amount of time for urllib3 to return96 an HTTP response. Specifically, Python's DNS resolver does not obey the97 timeout specified on the socket. Other factors that can affect total98 request time include high CPU load, high swap, the program running at a99 low priority level, or other behaviors. The observed running time for100 urllib3 to return a response may be greater than the value passed to101 `total`.102103 In addition, the read and total timeouts only measure the time between104 read operations on the socket connecting the client and the server, not105 the total amount of time for the request to return a complete response.106 As an example, you may want a request to return within 7 seconds or107 fail, so you set the ``total`` timeout to 7 seconds. If the server108 sends one byte to you every 5 seconds, the request will **not** trigger109 time out. This case is admittedly rare.110 """111112 #: A sentinel object representing the default timeout value113 DEFAULT_TIMEOUT = _GLOBAL_DEFAULT_TIMEOUT114115 def __init__(self, connect=_Default, read=_Default, total=None):116 self._connect = self._validate_timeout(connect, 'connect')117 self._read = self._validate_timeout(read, 'read')118 self.total = self._validate_timeout(total, 'total')119 self._start_connect = None120121 def __str__(self):122 return '%s(connect=%r, read=%r, total=%r)' % (123 type(self).__name__, self._connect, self._read, self.total)124125126 @classmethod127 def _validate_timeout(cls, value, name):128 """ Check that a timeout attribute is valid129130 :param value: The timeout value to validate131 :param name: The name of the timeout attribute to validate. This is used132 for clear error messages133 :return: the value134 :raises ValueError: if the type is not an integer or a float, or if it135 is a numeric value less than zero136 """137 if value is _Default:138 return cls.DEFAULT_TIMEOUT139140 if value is None or value is cls.DEFAULT_TIMEOUT:141 return value142143 try:144 float(value)145 except (TypeError, ValueError):146 raise ValueError("Timeout value %s was %s, but it must be an "147 "int or float." % (name, value))148149 try:150 if value < 0:151 raise ValueError("Attempted to set %s timeout to %s, but the "152 "timeout cannot be set to a value less "153 "than 0." % (name, value))154 except TypeError: # Python 3155 raise ValueError("Timeout value %s was %s, but it must be an "156 "int or float." % (name, value))157158 return value159160 @classmethod161 def from_float(cls, timeout):162 """ Create a new Timeout from a legacy timeout value.163164 The timeout value used by httplib.py sets the same timeout on the165 connect(), and recv() socket requests. This creates a :class:`Timeout`166 object that sets the individual timeouts to the ``timeout`` value passed167 to this function.168169 :param timeout: The legacy timeout value170 :type timeout: integer, float, sentinel default object, or None171 :return: a Timeout object172 :rtype: :class:`Timeout`173 """174 return Timeout(read=timeout, connect=timeout)175176 def clone(self):177 """ Create a copy of the timeout object178179 Timeout properties are stored per-pool but each request needs a fresh180 Timeout object to ensure each one has its own start/stop configured.181182 :return: a copy of the timeout object183 :rtype: :class:`Timeout`184 """185 # We can't use copy.deepcopy because that will also create a new object186 # for _GLOBAL_DEFAULT_TIMEOUT, which socket.py uses as a sentinel to187 # detect the user default.188 return Timeout(connect=self._connect, read=self._read,189 total=self.total)190191 def start_connect(self):192 """ Start the timeout clock, used during a connect() attempt193194 :raises urllib3.exceptions.TimeoutStateError: if you attempt195 to start a timer that has been started already.196 """197 if self._start_connect is not None:198 raise TimeoutStateError("Timeout timer has already been started.")199 self._start_connect = current_time()200 return self._start_connect201202 def get_connect_duration(self):203 """ Gets the time elapsed since the call to :meth:`start_connect`.204205 :return: the elapsed time206 :rtype: float207 :raises urllib3.exceptions.TimeoutStateError: if you attempt208 to get duration for a timer that hasn't been started.209 """210 if self._start_connect is None:211 raise TimeoutStateError("Can't get connect duration for timer "212 "that has not started.")213 return current_time() - self._start_connect214215 @property216 def connect_timeout(self):217 """ Get the value to use when setting a connection timeout.218219 This will be a positive float or integer, the value None220 (never timeout), or the default system timeout.221222 :return: the connect timeout223 :rtype: int, float, :attr:`Timeout.DEFAULT_TIMEOUT` or None224 """225 if self.total is None:226 return self._connect227228 if self._connect is None or self._connect is self.DEFAULT_TIMEOUT:229 return self.total230231 return min(self._connect, self.total)232233 @property234 def read_timeout(self):235 """ Get the value for the read timeout.236237 This assumes some time has elapsed in the connection timeout and238 computes the read timeout appropriately.239240 If self.total is set, the read timeout is dependent on the amount of241 time taken by the connect timeout. If the connection time has not been242 established, a :exc:`~urllib3.exceptions.TimeoutStateError` will be243 raised.244245 :return: the value to use for the read timeout246 :rtype: int, float, :attr:`Timeout.DEFAULT_TIMEOUT` or None247 :raises urllib3.exceptions.TimeoutStateError: If :meth:`start_connect`248 has not yet been called on this object.249 """250 if (self.total is not None and251 self.total is not self.DEFAULT_TIMEOUT and252 self._read is not None and253 self._read is not self.DEFAULT_TIMEOUT):254 # in case the connect timeout has not yet been established.255 if self._start_connect is None:256 return self._read257 return max(0, min(self.total - self.get_connect_duration(),258 self._read))259 elif self.total is not None and self.total is not self.DEFAULT_TIMEOUT:260 return max(0, self.total - self.get_connect_duration())261 else:262 return self._read263264265class Url(namedtuple('Url', ['scheme', 'auth', 'host', 'port', 'path', 'query', 'fragment'])):266 """267 Datastructure for representing an HTTP URL. Used as a return value for268 :func:`parse_url`.
358 unmodified lines
modified:requests/__init__.py+1 added-1 removed
48 unmodified lines
49__copyright__ = 'Copyright 2013 Kenneth Reitz'5051# Attempt to enable urllib3's SNI support, if possible52try:53 from requests.packages.urllib3.contrib import pyopenssl53 from .packages.urllib3.contrib import pyopenssl54 pyopenssl.inject_into_urllib3()55except ImportError:56 pass57
20 unmodified lines
modified:requests/adapters.py+40 added-13 removed
9 unmodified lines
1011import socket1213from .models import Response14from .packages.urllib3.poolmanager import PoolManager, ProxyManager14from .packages.urllib3.poolmanager import PoolManager, proxy_from_url15from .packages.urllib3.response import HTTPResponse16from .packages.urllib3.util import Timeout17from .compat import urlparse, basestring, urldefrag, unquote18from .utils import (DEFAULT_CA_BUNDLE_PATH, get_encoding_from_headers,18 prepend_scheme_if_needed, get_auth_from_url)19 except_on_missing_scheme, get_auth_from_url)20from .structures import CaseInsensitiveDict21from .packages.urllib3.exceptions import MaxRetryError22from .packages.urllib3.exceptions import TimeoutError23from .packages.urllib3.exceptions import SSLError as _SSLError
47 unmodified lines
71 pool_maxsize=DEFAULT_POOLSIZE, max_retries=DEFAULT_RETRIES,72 pool_block=DEFAULT_POOLBLOCK):73 self.max_retries = max_retries74 self.config = {}75 self.proxy_manager = {}7677 super(HTTPAdapter, self).__init__()7879 self._pool_connections = pool_connections
114 unmodified lines
194 proxies = proxies or {}195 proxy = proxies.get(urlparse(url.lower()).scheme)196197 if proxy:196 proxy = prepend_scheme_if_needed(proxy, urlparse(url.lower()).scheme)197 conn = ProxyManager(self.poolmanager.connection_from_url(proxy))198 except_on_missing_scheme(proxy)199 proxy_headers = self.proxy_headers(proxy)200201 if not proxy in self.proxy_manager:202 self.proxy_manager[proxy] = proxy_from_url(203 proxy,204 proxy_headers=proxy_headers)205206 conn = self.proxy_manager[proxy].connection_from_url(url)207 else:208 conn = self.poolmanager.connection_from_url(url.lower())209210 return conn
29 unmodified lines
240241 return url242243 def add_headers(self, request, **kwargs):235 """Add any headers needed by the connection. Currently this adds a236 Proxy-Authorization header.244 """Add any headers needed by the connection. As of v2.0 this does245 nothing by default, but is left for overriding by users that subclass246 the :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.247248 This should not be called from user code, and is only exposed for use249 when subclassing the250 :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.251252 :param request: The :class:`PreparedRequest <PreparedRequest>` to add headers to.253 :param kwargs: The keyword arguments from the call to send().254 """245 proxies = kwargs.get('proxies', {})255 pass256247 if proxies is None:248 proxies = {}257 def proxy_headers(self, proxy):258 """Returns a dictionary of the headers to add to any request sent259 through a proxy. This works with urllib3 magic to ensure that they are260 correctly sent to the proxy, rather than in a tunnelled request if261 CONNECT is being used.262250 proxy = proxies.get(urlparse(request.url).scheme)263 This should not be called from user code, and is only exposed for use264 when subclassing the265 :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.266267 :param proxies: The url of the proxy being used for this request.268 :param kwargs: Optional additional keyword arguments.269 """270 headers = {}271 username, password = get_auth_from_url(proxy)272273 if username and password:274 # Proxy auth usernames and passwords will be urlencoded, we need275 # to decode them.276 username = unquote(username)277 password = unquote(password)258 request.headers['Proxy-Authorization'] = _basic_auth_str(username,259 password)278 headers['Proxy-Authorization'] = _basic_auth_str(username,279 password)280281 return headers282283 def send(self, request, stream=False, timeout=None, verify=True, cert=None, proxies=None):284 """Sends PreparedRequest object. Returns Response object.285286 :param request: The :class:`PreparedRequest <PreparedRequest>` being sent.
7 unmodified lines
294 conn = self.get_connection(request.url, proxies)295296 self.cert_verify(conn, request.url, verify, cert)297 url = self.request_url(request, proxies)276 self.add_headers(request, proxies=proxies)298 self.add_headers(request)299300 chunked = not (request.body is None or 'Content-Length' in request.headers)301302 if stream:303 timeout = Timeout(connect=timeout)304 else:305 timeout = Timeout(connect=timeout, read=timeout)306307 try:308 if not chunked:309 resp = conn.urlopen(310 method=request.method,
59 unmodified lines
modified:requests/auth.py+9 added-6 removed
16 unmodified lines
1718from .compat import urlparse, str19from .utils import parse_dict_header202121log = logging.getLogger(__name__)2223CONTENT_TYPE_FORM_URLENCODED = 'application/x-www-form-urlencoded'24CONTENT_TYPE_MULTI_PART = 'multipart/form-data'
79 unmodified lines
104105 A1 = '%s:%s:%s' % (self.username, realm, self.password)106 A2 = '%s:%s' % (method, path)107109 if qop == 'auth':108 if qop is None:109 respdig = KD(hash_utf8(A1), "%s:%s" % (nonce, hash_utf8(A2)))110 elif qop == 'auth' or 'auth' in qop.split(','):111 if nonce == self.last_nonce:112 self.nonce_count += 1113 else:114 self.nonce_count = 1
6 unmodified lines
121122 cnonce = (hashlib.sha1(s).hexdigest()[:16])123 noncebit = "%s:%s:%s:%s:%s" % (nonce, ncvalue, cnonce, qop, hash_utf8(A2))124 respdig = KD(hash_utf8(A1), noncebit)124 elif qop is None:125 respdig = KD(hash_utf8(A1), "%s:%s" % (nonce, hash_utf8(A2)))125 else:126 # XXX handle auth-int.127 return None128
28 unmodified lines
157 # Consume content and release the original connection158 # to allow our new request to reuse the same one.159 r.content160 r.raw.release_conn()161 prep = r.request.copy()162 prep.prepare_cookies(r.cookies)163163 r.request.headers['Authorization'] = self.build_digest_header(r.request.method, r.request.url)164 _r = r.connection.send(r.request, **kwargs)164 prep.headers['Authorization'] = self.build_digest_header(165 prep.method, prep.url)166 _r = r.connection.send(prep, **kwargs)167 _r.history.append(r)168 _r.request = prep169170 return _r171172 setattr(self, 'num_401_calls', 1)
8 unmodified lines
modified:requests/exceptions.py+1 added-1 removed
7 unmodified lines
89"""101112class RequestException(RuntimeError):12class RequestException(IOError):13 """There was an ambiguous exception that occurred while handling your14 request."""1516
43 unmodified lines
modified:requests/models.py+13 added-7 removed
9 unmodified lines
10import collections11import logging12import datetime1314from io import BytesIO14from io import BytesIO, UnsupportedOperation15from .hooks import default_hooks16from .structures import CaseInsensitiveDict1718from .auth import HTTPBasicAuth
5 unmodified lines
24 ChunkedEncodingError)25from .utils import (26 guess_filename, get_auth_from_url, requote_uri,27 stream_decode_response_unicode, to_key_val_list, parse_header_links,28 iter_slices, guess_json_utf, super_len)28 iter_slices, guess_json_utf, super_len, to_native_string)29from .compat import (30 cookielib, urlunparse, urlsplit, urlencode, str, bytes, StringIO,31 is_py2, chardet, json, builtin_str, basestring, IncompleteRead)32
74 unmodified lines
107 if isinstance(val, basestring) or not hasattr(val, '__iter__'):108 val = [val]109 for v in val:110 if v is not None:111 # Don't call str() on bytestrings: in Py3 it all goes wrong.112 if not isinstance(v, bytes):113 v = str(v)114115 new_fields.append(116 (field.decode('utf-8') if isinstance(field, bytes) else field,117 v.encode('utf-8') if isinstance(v, str) else v))118
27 unmodified lines
146class RequestHooksMixin(object):147 def register_hook(self, event, hook):148 """Properly register a hook."""149150 if event not in self.hooks:151 raise ValueError('Unsupported event specified, with event name "%s"' % (event))152153 if isinstance(hook, collections.Callable):154 self.hooks[event].append(hook)155 elif hasattr(hook, '__iter__'):156 self.hooks[event].extend(h for h in hook if isinstance(h, collections.Callable))
37 unmodified lines
194 method=None,195 url=None,196 headers=None,197 files=None,191 data=dict(),192 params=dict(),198 data=None,199 params=None,200 auth=None,201 cookies=None,202 hooks=None):203
165 unmodified lines
369 def prepare_headers(self, headers):370 """Prepares the given HTTP headers."""371372 if headers:366 headers = dict((name.encode('ascii'), value) for name, value in headers.items())367 self.headers = CaseInsensitiveDict(headers)373 self.headers = CaseInsensitiveDict((to_native_string(name), value) for name, value in headers.items())374 else:375 self.headers = CaseInsensitiveDict()376377 def prepare_body(self, data, files):
15 unmodified lines
393 ])394395 try:396 length = super_len(data)391 except (TypeError, AttributeError):397 except (TypeError, AttributeError, UnsupportedOperation):398 length = None399400 if is_stream:401 body = data
329 unmodified lines
modified:requests/sessions.py+5 added-4 removed
72 unmodified lines
73 i = 07475 # ((resp.status_code is codes.see_other))76 while (('location' in resp.headers and resp.status_code in REDIRECT_STATI)):77 prepared_request = PreparedRequest()78 prepared_request.body = req.body79 prepared_request.headers = req.headers.copy()80 prepared_request.hooks = req.hooks77 prepared_request = req.copy()7879 resp.content # Consume socket so it can be released8081 if i >= self.max_redirects:
382 unmodified lines
464 # Response manipulation hooks465 r = dispatch_hook('response', hooks, r, **kwargs)466467 # Persist cookies468 if r.history:469 # If the hooks create history then we want those cookies too470 for resp in r.history:471 extract_cookies_to_jar(self.cookies, resp.request, resp.raw)472 extract_cookies_to_jar(self.cookies, request, r.raw)473474 # Redirect resolving generator.475 gen = self.resolve_redirects(r, request, stream=stream,
52 unmodified lines
modified:requests/utils.py+38 added-19 removed
19 unmodified lines
2021from . import __version__22from . import certs23from .compat import parse_http_list as _parse_list_header24from .compat import quote, urlparse, bytes, str, OrderedDict, urlunparse25from .compat import getproxies, proxy_bypass24from .compat import (quote, urlparse, bytes, str, OrderedDict, urlunparse,25 is_py2, is_py3, builtin_str, getproxies, proxy_bypass)26from .cookies import RequestsCookieJar, cookiejar_from_dict27from .structures import CaseInsensitiveDict28from .exceptions import MissingSchema, InvalidURL2930_hush_pyflakes = (RequestsCookieJar,)3132NETRC_FILES = ('.netrc', '_netrc')
333 unmodified lines
366 parts = uri.split('%')367 for i in range(1, len(parts)):368 h = parts[i][0:2]369 if len(h) == 2 and h.isalnum():370 try:369 c = chr(int(h, 16))371 c = chr(int(h, 16))372 except ValueError:373 raise InvalidURL("Invalid percent-escape sequence: '%s'" % h)374375 if c in UNRESERVED_SET:376 parts[i] = c + parts[i][2:]377 else:378 parts[i] = '%' + parts[i]
22 unmodified lines
401 # First check whether no_proxy is defined. If it is, check that the URL402 # we're getting isn't in the no_proxy list.403 no_proxy = get_proxy('no_proxy')404 netloc = urlparse(url).netloc400 405406 if no_proxy:407 # We need to check whether we match here. We need to see if we match408 # the end of the netloc, both with and without the port.404 no_proxy = no_proxy.split(',')405 409 no_proxy = no_proxy.replace(' ', '').split(',')410411 for host in no_proxy:412 if netloc.endswith(host) or netloc.split(':')[0].endswith(host):413 # The URL does match something in no_proxy, so we don't want414 # to apply the proxies on this URL.415 return {}411 416417 # If the system proxy settings indicate that this URL should be bypassed,418 # don't proxy.419 if proxy_bypass(netloc):420 return {}
1 unmodified line
422 # If we get here, we either didn't have no_proxy set or we're not going423 # anywhere that no_proxy applies to, and the system settings don't require424 # bypassing the proxy for the current URL.425 return getproxies()421 426427428def default_user_agent():429 """Return a string representing the default user agent."""430 _implementation = platform.python_implementation()431
100 unmodified lines
532 # Did not detect a valid UTF-32 ascii-range character533 return None534535531def prepend_scheme_if_needed(url, new_scheme):532 '''Given a URL that may or may not have a scheme, prepend the given scheme.533 Does not replace a present scheme with the one provided as an argument.'''534 scheme, netloc, path, params, query, fragment = urlparse(url, new_scheme)536def except_on_missing_scheme(url):537 """Given a URL, raise a MissingSchema exception if the scheme is missing.538 """539 scheme, netloc, path, params, query, fragment = urlparse(url)540536 # urlparse is a finicky beast, and sometimes decides that there isn't a537 # netloc present. Assume that it's being over-cautious, and switch netloc538 # and path if urlparse decided there was no netloc.539 if not netloc:540 netloc, path = path, netloc541 if not scheme:542 raise MissingSchema('Proxy URLs must have explicit schemes.')543542 return urlunparse((scheme, netloc, path, params, query, fragment))544544545def get_auth_from_url(url):546 """Given a url with authentication components, extract them into a tuple of547 username,password."""548 if url:549 parsed = urlparse(url)550 return (parsed.username, parsed.password)551 else:552 return ('', '')553554555def to_native_string(string, encoding='ascii'):556 """557 Given a string object, regardless of type, returns a representation of that558 string in the native string type, encoding and decoding where necessary.559 This assumes ASCII unless told otherwise.560 """561 out = None562563 if isinstance(string, builtin_str):564 out = string565 else:566 if is_py2:567 out = string.encode(encoding)568 else:569 out = string.decode(encoding)570571 return out
modified:AUTHORS.rst+1 added
133 unmodified lines
134- Flavio Curella135- David Pursehouse <david.pursehouse@gmail.com> @dpursehouse136- Jon Parise137- Alexander Karpinsky @homm86138- Marc Schlaich @schlamar
modified:HISTORY.rst+44 added
1 unmodified line
23History4-------562.0.0 (2013-XX-XX)7++++++++++++++++++89**API Changes:**1011- Keys in the Headers dictionary are now native strings on all Python versions,12 i.e. bytestrings on Python 2, unicode on Python 3.13- Proxy URLs now *must* have an explicit scheme. A ``MissingSchema`` exception14 will be raised if they don't.15- ``RequestException`` is now a subclass of ``IOError``, not ``RuntimeError``.16- Added new method to ``PreparedRequest`` objects: ``PreparedRequest.copy()``.17- Added new method to ``Session`` objects: ``Session.update_request()``. This18 method updates a ``Request`` object with the data (e.g. cookies) stored on19 the ``Session``.20- Added new method to ``Session`` objects: ``Session.prepare_request()``. This21 method updates and prepares a ``Request`` object, and returns the22 corresponding ``PreparedRequest`` object.23- Added new method to ``HTTPAdapter`` objects: ``HTTPAdapter.proxy_headers()``.24 This should not be called directly, but improves the subclass interface.25- ``httplib.IncompleteRead`` exceptions caused by incorrect chunked encoding26 will now raise a Requests ``ChunkedEncodingError`` instead.27- Invalid percent-escape sequences now cause a Requests ``InvalidURL``28 exception to be raised.29- HTTP 208 no longer uses reason phrase ``"im_used"``. Correctly uses30 ``"already_reported"``.31- HTTP 226 reason added (``"im_used"``).3233**Bugfixes:**3435- Vastly improved proxy support, including the CONNECT verb. Special thanks to36 the many contributors who worked towards this improvement.37- Chunked encoding fixes.38- Support for mixed case schemes.39- Retrieve environment proxies from more locations.40- Minor cookies fixes.41- Improved streaming behaviour, particularly for compressed data.42- Miscellaneous small Python 3 text encoding bugs.43- ``.netrc`` no longer overrides explicit auth.44- Cookies set by hooks are now correctly persisted on Sessions.45- Fix problem with cookies that specify port numbers in their host field.46- ``BytesIO`` can be used to perform streaming uploads.47- More generous parsing of the ``no_proxy`` environment variable.48- Non-string objects can be passed in data values alongside files.49501.2.3 (2013-05-25)51++++++++++++++++++5253- Simple packaging fix
650 unmodified lines
modified:README.rst+1 added
52 unmodified lines
53- Unicode Response Bodies54- Multipart File Uploads55- Connection Timeouts56- Thread-safety57- HTTP(S) proxy support585960Installation61------------
34 unmodified lines
modified:test_requests.py+41 added-8 removed
180 unmodified lines
181 # Make sure the cookie was sent182 assert r.json()['cookies']['foo'] == 'bar'183 # Make sure the session cj is still the custom one184 assert s.cookies is cj185 185186 def test_requests_in_history_are_not_overridden(self):187 resp = requests.get(httpbin('redirect/3'))188 urls = [r.url for r in resp.history]189 req_urls = [r.request.url for r in resp.history]190 self.assertEquals(urls, req_urls)191 191192 def test_user_agent_transfers(self):193194 heads = {195 'User-agent': 'Mozilla/5.0 (github.com/kennethreitz/requests)'
49 unmodified lines
245 r = requests.get(url, auth=wrong_auth)246 self.assertEqual(r.status_code, 401)247248 s = requests.session()249 249250 # Should use netrc and work.251 r = s.get(url)252 self.assertEqual(r.status_code, 200)253
13 unmodified lines
267 r = requests.get(url)268 self.assertEqual(r.status_code, 401)269270 s = requests.session()271 s.auth = auth271 s.auth = HTTPDigestAuth('user', 'pass')272 r = s.get(url)273 self.assertEqual(r.status_code, 200)274275 def test_DIGEST_AUTH_RETURNS_COOKIE(self):276 url = httpbin('digest-auth', 'auth', 'user', 'pass')277 auth = HTTPDigestAuth('user', 'pass')278 r = requests.get(url)279 assert r.cookies['fake'] == 'fake_value'280281 r = requests.get(url, auth=auth)282 assert r.status_code == 200283284 def test_DIGEST_AUTH_SETS_SESSION_COOKIES(self):285 url = httpbin('digest-auth', 'auth', 'user', 'pass')286 auth = HTTPDigestAuth('user', 'pass')287 s = requests.Session()288 s.get(url, auth=auth)289 assert s.cookies['fake'] == 'fake_value'290291 def test_DIGEST_STREAM(self):292293 auth = HTTPDigestAuth('user', 'pass')294 url = httpbin('digest-auth', 'auth', 'user', 'pass')
283 unmodified lines
578 s.headers.update({'ACCEPT': 'BOGUS'})579 s.headers.update({'accept': 'application/json'})580 r = s.get(httpbin('get'))581 headers = r.request.headers566 # ASCII encode because of key comparison changes in py3582 self.assertEqual(568 headers['accept'.encode('ascii')],583 headers['accept'],584 'application/json'585 )586 self.assertEqual(572 headers['Accept'.encode('ascii')],587 headers['Accept'],588 'application/json'589 )590 self.assertEqual(576 headers['ACCEPT'.encode('ascii')],591 headers['ACCEPT'],592 'application/json'593 )594595 def test_uppercase_scheme_redirect(self):
63 unmodified lines
659 )660 r = requests.Request('GET', url).prepare()661 self.assertEqual(r.url, url)662663 def test_header_keys_are_native(self):664 headers = {u'unicode': 'blah', 'byte'.encode('ascii'): 'blah'}665 r = requests.Request('GET', httpbin('get'), headers=headers)666 p = r.prepare()667668 # This is testing that they are builtin strings. A bit weird, but there669 # we go.670 self.assertTrue('unicode' in p.headers.keys())671 self.assertTrue('byte' in p.headers.keys())672673 def test_can_send_nonstring_objects_with_files(self):674 data = {'a': 0.0}675 files = {'b': 'foo'}676 r = requests.Request('POST', httpbin('post'), data=data, files=files)677 p = r.prepare()678679 self.assertTrue('multipart/form-data' in p.headers['Content-Type'])680681682class TestContentEncodingDetection(unittest.TestCase):683684 def test_none(self):685 encodings = requests.utils.get_encodings_from_content('')
186 unmodified lines