Skip to content
Myr

urllib3 updates

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 · parent df66fa7 · Browse files · 7 files+492 added−173 removed
This commit

State

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

Diff stats

7 files+492 added−173 removed

  • other:+492 added−173 removed

7 files+492 added−173 removed

modified:requests/packages/urllib3/__init__.py+14 added-10 removed
1"""2urllib3 - Thread-safe connection pooling and re-using.3"""45from connectionpool import (6 connection_from_url,7 get_host,5__author__ = "Andrey Petrov (andrey.petrov@shazow.net)"6__license__ = "MIT"7__version__ = "$Rev$"8910from .connectionpool import (11 HTTPConnectionPool,12 HTTPSConnectionPool,13 connection_from_url,14 get_host,15 make_headers)11# Possible exceptions12from connectionpool import (161718from .exceptions import (19 HTTPError,20 MaxRetryError,21 SSLError,22 TimeoutError)17from filepost import encode_multipart_formdata231920__author__ = "Andrey Petrov (andrey.petrov@shazow.net)"21__license__ = "MIT"22__version__ = "$Rev$"24from .poolmanager import PoolManager25from .response import HTTPResponse26from .filepost import encode_multipart_formdata
added:requests/packages/urllib3/_collections.py+115 added
1from collections import MutableMapping, deque234__all__ = ['RecentlyUsedContainer']567class AccessEntry(object):8 __slots__ = ('key', 'is_valid')910 def __init__(self, key, is_valid=True):11 self.key = key12 self.is_valid = is_valid131415class RecentlyUsedContainer(MutableMapping):16 """17 Provides a dict-like that maintains up to ``maxsize`` keys while throwing18 away the least-recently-used keys beyond ``maxsize``.19 """2021 # TODO: Make this threadsafe. _prune_invalidated_entries should be the22 # only real pain-point for this.2324 # If len(self.access_log) exceeds self._maxsize * CLEANUP_FACTOR, then we25 # will attempt to cleanup the invalidated entries in the access_log26 # datastructure during the next 'get' operation.27 CLEANUP_FACTOR = 102829 def __init__(self, maxsize=10):30 self._maxsize = maxsize3132 self._container = {}3334 # We use a deque to to store our keys ordered by the last access.35 self.access_log = deque()3637 # We look up the access log entry by the key to invalidate it so we can38 # insert a new authorative entry at the head without having to dig and39 # find the old entry for removal immediately.40 self.access_lookup = {}4142 # Trigger a heap cleanup when we get past this size43 self.access_log_limit = maxsize * self.CLEANUP_FACTOR4445 def _push_entry(self, key):46 "Push entry onto our access log, invalidate the old entry if exists."47 # Invalidate old entry if it exists48 old_entry = self.access_lookup.get(key)49 if old_entry:50 old_entry.is_valid = False5152 new_entry = AccessEntry(key)5354 self.access_lookup[key] = new_entry55 self.access_log.appendleft(new_entry)5657 def _prune_entries(self, num):58 "Pop entries from our access log until we popped ``num`` valid ones."59 while num > 0:60 p = self.access_log.pop()6162 if not p.is_valid:63 continue # Invalidated entry, skip6465 del self._container[p.key]66 del self.access_lookup[p.key]67 num -= 16869 def _prune_invalidated_entries(self):70 "Rebuild our access_log without the invalidated entries."71 self.access_log = deque(e for e in self.access_log if e.is_valid)7273 def _get_ordered_access_keys(self):74 # Used for testing75 return [e.key for e in self.access_log if e.is_valid]7677 def __getitem__(self, key):78 item = self._container.get(key)7980 if not item:81 return8283 # Insert new entry with new high priority, also implicitly invalidates84 # the old entry.85 self._push_entry(key)8687 if len(self.access_log) > self.access_log_limit:88 # Heap is getting too big, try to clean up any tailing invalidated89 # entries.90 self._prune_invalidated_entries()9192 return item9394 def __setitem__(self, key, item):95 # Add item to our container and access log96 self._container[key] = item97 self._push_entry(key)9899 # Discard invalid and excess entries100 self._prune_entries(len(self._container) - self._maxsize)101102103 def __delitem__(self, key):104 self._invalidate_entry(key)105 del self._container[key]106 del self._access_lookup[key]107108 def __len__(self):109 return len(self.access_log)110111 def __iter__(self):112 return self._container.__iter__()113114 def __contains__(self, key):115 return self._container.__contains__(key)
modified:requests/packages/urllib3/connectionpool.py+88 added-156 removed
1import gzip2import zlib1import logging2import socket34
6 unmodified lines
1112try:13 import ssl14 BaseSSLError = ssl.SSLError17except ImportError, e:15except ImportError:16 ssl = None17 BaseSSLError = None1821try:22 from cStringIO import StringIO23except ImportError, e:24 from StringIO import StringIO1920from .filepost import encode_multipart_formdata21from .response import HTTPResponse22from .exceptions import (23 SSLError,24 MaxRetryError,25 TimeoutError,26 HostChangedError,27 EmptyPoolError)2827from filepost import encode_multipart_formdata292930log = logging.getLogger(__name__)313233## Exceptions33## Connection objects (extension of httplib)3435class HTTPError(Exception):36 "Base exception used by this module."37 pass383940class SSLError(Exception):41 "Raised when SSL certificate fails in an HTTPS connection."42 pass434445class MaxRetryError(HTTPError):46 "Raised when the maximum number of retries is exceeded."47 pass484950class TimeoutError(HTTPError):51 "Raised when a socket timeout occurs."52 pass535455class HostChangedError(HTTPError):56 "Raised when an existing pool gets a request for a foreign host."57 pass585960## Response objects6162class HTTPResponse(object):63 """64 HTTP Response container.6566 Similar to httplib's HTTPResponse but the data is pre-loaded.67 """6869 def __init__(self, data='', headers=None, status=0, version=0, reason=None,70 strict=0):71 self.data = data72 self.headers = headers or {}73 self.status = status74 self.version = version75 self.reason = reason76 self.strict = strict7778 @staticmethod79 def from_httplib(r, block=True):80 """81 Given an httplib.HTTPResponse instance, return a corresponding82 urllib3.HTTPResponse object.8384 NOTE: This method will perform r.read() which will have side effects85 on the original http.HTTPResponse object.86 """8788 if block:89 tmp_data = r.read()90 try:91 if r.getheader('content-encoding') == 'gzip':92 log.debug("Received response with content-encoding: gzip, "93 "decompressing with gzip.")9495 gzipper = gzip.GzipFile(fileobj=StringIO(tmp_data))96 data = gzipper.read()97 elif r.getheader('content-encoding') == 'deflate':98 log.debug("Received response with content-encoding: deflate, "99 "decompressing with zlib.")100 try:101 data = zlib.decompress(tmp_data)102 except zlib.error, e:103 data = zlib.decompress(tmp_data, -zlib.MAX_WBITS)104 else:105 data = tmp_data106107 except IOError:108 raise HTTPError("Received response with content-encoding: %s, "109 "but failed to decompress it." %110 (r.getheader('content-encoding')))111 else:112 data = None113114 resp = HTTPResponse(data=data,115 headers=dict(r.getheaders()),116 status=r.status,117 version=r.version,118 reason=r.reason,119 strict=r.strict)120121 resp._raw = r122 return resp123124 # Backwards-compatibility methods for httplib.HTTPResponse125 def getheaders(self):126 return self.headers127128 def getheader(self, name, default=None):129 return self.headers.get(name, default)130131132## Connection objects13335class VerifiedHTTPSConnection(HTTPSConnection):36 """37 Based on httplib.HTTPSConnection but wraps the socket with38 SSL certification.39 """4041 def __init__(self):42 HTTPSConnection.__init__()43 self.cert_reqs = None44 self.ca_certs = None45140 def set_cert(self, key_file=None, cert_file=None, cert_reqs='CERT_NONE',141 ca_certs=None):46 def set_cert(self, key_file=None, cert_file=None,47 cert_reqs='CERT_NONE', ca_certs=None):48 ssl_req_scheme = {49 'CERT_NONE': ssl.CERT_NONE,50 'CERT_OPTIONAL': ssl.CERT_OPTIONAL,51 'CERT_REQUIRED': ssl.CERT_REQUIRED
16 unmodified lines
686970## Pool objects71166class HTTPConnectionPool(object):72class ConnectionPool(object):73 pass747576class HTTPConnectionPool(ConnectionPool):77 """78 Thread-safe connection pool for one host.7980 host
43 unmodified lines
124 self.block = block125 self.headers = headers or {}126127 # Fill the queue up so that doing get() on it will block properly218 [self.pool.put(None) for i in xrange(maxsize)]128 for _ in xrange(maxsize):129 self.pool.put(None)130131 # These are mostly for testing and debugging purposes.132 self.num_connections = 0133 self.num_requests = 0134135 def _new_conn(self):
16 unmodified lines
152153 # If this is a persistent connection, check if it got disconnected154 if conn and conn.sock and select([conn.sock], [], [], 0.0)[0]:155 # Either data is buffered (bad), or the connection is dropped.244 log.warning("Connection pool detected dropped "245 "connection, resetting: %s" % self.host)156 log.info("Resetting dropped connection: %s" % self.host)157 conn.close()158248 except Empty, e:159 except Empty:160 if self.block:161 raise EmptyPoolError("Pool reached maximum size and no more "162 "connections are allowed.")163 pass # Oh well, we'll create a new connection then164165 return conn or self._new_conn()166
5 unmodified lines
172 should be increased.173 """174 try:175 self.pool.put(conn, block=False)262 except Full, e:176 except Full:177 # This should never happen if self.block == True178 log.warning("HttpConnectionPool is full, discarding connection: %s"179 % self.host)180181 def _make_request(self, conn, method, url, **httplib_request_kw):182 """183 Perform a request on a given httplib connection object taken from our184 pool.185 """186 self.num_requests += 1187188 conn.request(method, url, **httplib_request_kw)189 conn.sock.settimeout(self.timeout)190 httplib_response = conn.getresponse()191192 log.debug("\"%s %s %s\" %s %s" %193 (method, url,194 conn._http_vsn_str, # pylint: disable-msg=W0212195 httplib_response.status, httplib_response.length))196197 return httplib_response198199200 def is_same_host(self, url):201 return (url.startswith('/') or202 get_host(url) == (self.scheme, self.host, self.port))203204 def urlopen(self, method, url, body=None, headers=None, retries=3,272 redirect=True, assert_same_host=True, block=True):205 redirect=True, assert_same_host=True, pool_timeout=None,206 **response_kw):207 """208 Get a connection from the pool and perform an HTTP request.209210 method
20 unmodified lines
231 assert_same_host232 If True, will make sure that the host of the pool requests is233 consistent else will raise HostChangedError. When False, you can234 use the pool on an HTTP proxy and request foreign hosts.235236 pool_timeout237 If set and the pool is set to block=True, then this method will238 block for ``pool_timeout`` seconds and raise EmptyPoolError if no239 connection is available within the time period.240241 Additional parameters are passed to242 ``HTTPResponse.from_httplib(r, **response_kw)``243 """302 if headers == None:244 if headers is None:245 headers = self.headers246247 if retries < 0:248 raise MaxRetryError("Max retries exceeded for url: %s" % url)
8 unmodified lines
257 "open a foreign host: %s" % (host, url))258259 try:260 # Request a connection from the queue319 conn = self._get_conn()261 conn = self._get_conn(timeout=pool_timeout)262321 # Make the request322 self.num_requests += 1323 conn.request(method, url, body=body, headers=headers)324 conn.sock.settimeout(self.timeout)325 httplib_response = conn.getresponse()326 log.debug("\"%s %s %s\" %s %s" %327 (method, url, conn._http_vsn_str,328 httplib_response.status, httplib_response.length))263 # Make the request on the httplib connection object264 httplib_response = self._make_request(conn, method, url,265 body=body, headers=headers)266330 # from_httplib will perform httplib_response.read() which will have331 # the side effect of letting us use this connection for another332 # request.333 response = HTTPResponse.from_httplib(httplib_response, block=block)267 # Import httplib's response into our own wrapper object268 response = HTTPResponse.from_httplib(httplib_response,269 pool=self,270 connection=conn,271 **response_kw)272335 # Put the connection back to be reused336 self._put_conn(conn)273 # The connection will be put back into the pool when274 # response.release_conn() is called (implicitly by response.read())275276 except (SocketTimeout, Empty), e:277 # Timed out either by socket or queue278 raise TimeoutError("Request timed out after %f seconds" %
21 unmodified lines
300301 return response302303 def get_url(self, url, fields=None, headers=None, retries=3,366 redirect=True):304 redirect=True, **response_kw):305 """306 Wrapper for performing GET with urlopen (see urlopen for more details).307308 Supports an optional ``fields`` dictionary parameter key/value strings.
1 unmodified line
310 """311 if fields:312 url += '?' + urlencode(fields)313 return self.urlopen('GET', url, headers=headers, retries=retries,376 redirect=redirect)314 redirect=redirect, **response_kw)315316 def post_url(self, url, fields=None, headers=None, retries=3,379 redirect=True, encode_multipart=True):317 redirect=True, encode_multipart=True, multipart_boundary=None,318 **response_kw):319 """320 Wrapper for performing POST with urlopen (see urlopen321 for more details).322
19 unmodified lines
342 overwritten because it depends on the dynamic random boundary string343 which is used to compose the body of the request.344 """345 if encode_multipart:407 body, content_type = encode_multipart_formdata(fields or {})346 body, content_type = encode_multipart_formdata(fields or {},347 boundary=multipart_boundary)348 else:349 body, content_type = (350 urlencode(fields or {}),351 'application/x-www-form-urlencoded')
1 unmodified line
353 headers = headers or {}354 headers.update({'Content-Type': content_type})355356 return self.urlopen('POST', url, body, headers=headers,417 retries=retries, redirect=redirect)357 retries=retries, redirect=redirect, **response_kw)358359360class HTTPSConnectionPool(HTTPConnectionPool):361 """
1 unmodified line
363 """364365 scheme = 'https'366427 def __init__(self, host, port=None, strict=False, timeout=None, maxsize=1,428 block=False, headers=None, key_file=None,429 cert_file=None, cert_reqs='CERT_NONE', ca_certs=None):430 self.host = host431 self.port = port432 self.strict = strict433 self.timeout = timeout434 self.pool = Queue(maxsize)435 self.block = block436 self.headers = headers or {}367 def __init__(self, host, port=None,368 strict=False, timeout=None, maxsize=1,369 block=False, headers=None,370 key_file=None, cert_file=None,371 cert_reqs='CERT_NONE', ca_certs=None):372373 super(HTTPSConnectionPool, self).__init__(host, port,374 strict, timeout, maxsize,375 block, headers)376 self.key_file = key_file377 self.cert_file = cert_file378 self.cert_reqs = cert_reqs379 self.ca_certs = ca_certs380443 # Fill the queue up so that doing get() on it will block properly444 [self.pool.put(None) for i in xrange(maxsize)]445446 self.num_connections = 0447 self.num_requests = 0448381 def _new_conn(self):382 """383 Return a fresh HTTPSConnection.384 """
73 unmodified lines
458 scheme = 'http'459 if '//' in url:460 scheme, url = url.split('://', 1)461 if '/' in url:530 url, path = url.split('/', 1)462 url, _path = url.split('/', 1)463 if ':' in url:464 url, port = url.split(':', 1)465 port = int(port)466 return scheme, url, port
17 unmodified lines
added:requests/packages/urllib3/exceptions.py+29 added
1## Exceptions23class HTTPError(Exception):4 "Base exception used by this module."5 pass678class SSLError(Exception):9 "Raised when SSL certificate fails in an HTTPS connection."10 pass111213class MaxRetryError(HTTPError):14 "Raised when the maximum number of retries is exceeded."15 pass161718class TimeoutError(HTTPError):19 "Raised when a socket timeout occurs."20 pass212223class HostChangedError(HTTPError):24 "Raised when an existing pool gets a request for a foreign host."25 pass2627class EmptyPoolError(HTTPError):28 "Raised when a pool runs out of connections and no more are allowed."29 pass
modified:requests/packages/urllib3/filepost.py+9 added-7 removed
1import codecs2import mimetools3import mimetypes45try:6 from cStringIO import StringIO6except:7 from StringIO import StringIO7except ImportError:8 from StringIO import StringIO # pylint: disable-msg=W040491011writer = codecs.lookup('utf-8')[3]12
1 unmodified line
14def get_content_type(filename):15 return mimetypes.guess_type(filename)[0] or 'application/octet-stream'161717def encode_multipart_formdata(fields):18def encode_multipart_formdata(fields, boundary=None):19 body = StringIO()20 if boundary is None:19 BOUNDARY = mimetools.choose_boundary()21 boundary = mimetools.choose_boundary()2223 for fieldname, value in fields.iteritems():22 body.write('--%s\r\n' % (BOUNDARY))24 body.write('--%s\r\n' % (boundary))2526 if isinstance(value, tuple):27 filename, data = value28 writer(body).write('Content-Disposition: form-data; name="%s"; '
15 unmodified lines
44 body.write(data)4546 body.write('\r\n')4746 body.write('--%s--\r\n' % (BOUNDARY))48 body.write('--%s--\r\n' % (boundary))4948 content_type = 'multipart/form-data; boundary=%s' % BOUNDARY50 content_type = 'multipart/form-data; boundary=%s' % boundary5152 return body.getvalue(), content_type
added:requests/packages/urllib3/poolmanager.py+64 added
1from ._collections import RecentlyUsedContainer2from .connectionpool import HTTPConnectionPool, HTTPSConnectionPool, get_host345pool_classes_by_scheme = {6 'http': HTTPConnectionPool,7 'https': HTTPSConnectionPool,8}910port_by_scheme = {11 'http': 80,12 'https': 433,13}141516class PoolManager(object):17 """18 Allows for arbitrary requests while transparently keeping track of19 necessary connection pools for you.2021 num_pools22 Number of connection pools to cache before discarding the least recently23 used pool.2425 Additional parameters are used to create fresh ConnectionPool instances.2627 """2829 # TODO: Make sure there are no memory leaks here.3031 def __init__(self, num_pools=10, **connection_pool_kw):32 self.connection_pool_kw = connection_pool_kw3334 self.pools = RecentlyUsedContainer(num_pools)35 self.recently_used_pools = []3637 def connection_from_url(self, url):38 """39 Similar to connectionpool.connection_from_url but doesn't pass any40 additional keywords to the ConnectionPool constructor. Additional41 keywords are taken from the PoolManager constructor.42 """43 scheme, host, port = get_host(url)4445 # If the scheme, host, or port doesn't match existing open connections,46 # open a new ConnectionPool.47 pool_key = (scheme, host, port or port_by_scheme.get(scheme, 80))4849 pool = self.pools.get(pool_key)50 if pool:51 return pool5253 # Make a fresh ConnectionPool of the desired type54 pool_cls = pool_classes_by_scheme[scheme]55 pool = pool_cls(host, port, **self.connection_pool_kw)5657 self.pools[pool_key] = pool5859 return pool6061 def urlopen(self, method, url, **kw):62 "Same as HTTP(S)ConnectionPool.urlopen"63 conn = self.connection_from_url(url)64 return conn.urlopen(method, url, **kw)
added:requests/packages/urllib3/response.py+173 added
1import gzip2import logging3import zlib456try:7 from cStringIO import StringIO8except ImportError:9 from StringIO import StringIO # pylint: disable-msg=W0404101112from .exceptions import HTTPError131415log = logging.getLogger(__name__)161718def decode_gzip(data):19 gzipper = gzip.GzipFile(fileobj=StringIO(data))20 return gzipper.read()212223def decode_deflate(data):24 try:25 return zlib.decompress(data)26 except zlib.error:27 return zlib.decompress(data, -zlib.MAX_WBITS)282930class HTTPResponse(object):31 """32 HTTP Response container.3334 Backwards-compatible to httplib's HTTPResponse but the response ``body`` is35 loaded and decoded on-demand when the ``data`` property is accessed.3637 Extra parameters for behaviour not present in httplib.HTTPResponse:3839 preload_content40 If True, the response's body will be preloaded during construction.4142 decode_content43 If True, attempts to decode specific content-encoding's based on headers44 (like 'gzip' and 'deflate') will be skipped and raw data will be used45 instead.4647 original_response48 When this HTTPResponse wrapper is generated from an httplib.HTTPResponse49 object, it's convenient to include the original for debug purposes. It's50 otherwise unused.51 """5253 CONTENT_DECODERS = {54 'gzip': decode_gzip,55 'deflate': decode_deflate,56 }5758 def __init__(self, body='', headers=None, status=0, version=0, reason=None,59 strict=0, preload_content=False, decode_content=True,60 original_response=None, pool=None, connection=None):61 self.headers = headers or {}62 self.status = status63 self.version = version64 self.reason = reason65 self.strict = strict6667 self._decode_content = decode_content68 self._body = None69 self._fp = None70 self._original_response = original_response7172 self._pool = pool73 self._connection = connection7475 if hasattr(body, 'read'):76 self._fp = body7778 if preload_content:79 self._body = self.read(decode_content=decode_content)8081 def release_conn(self):82 if not self._pool or not self._connection:83 return8485 self._pool._put_conn(self._connection)8687 @property88 def data(self):89 # For backwords-compat with earlier urllib3 0.4 and earlier.90 if self._body:91 return self._body9293 if self._fp:94 return self.read(decode_content=self._decode_content,95 cache_content=True)9697 def read(self, amt=None, decode_content=True, cache_content=False):98 """99 Similar to ``httplib.HTTPResponse.read(amt=None)``.100101 amt102 How much of the content to read. If specified, decoding and caching103 is skipped because we can't decode partial content nor does it make104 sense to cache partial content as the full response.105106 decode_content107 If True, will attempt to decode the body based on the108 'content-encoding' header. (Overridden if ``amt`` is set.)109110 cache_content111 If True, will save the returned data such that the same result is112 returned despite of the state of the underlying file object. This113 is useful if you want the ``.data`` property to continue working114 after having ``.read()`` the file object. (Overridden if ``amt`` is115 set.)116 """117 content_encoding = self.headers.get('content-encoding')118 decoder = self.CONTENT_DECODERS.get(content_encoding)119120 data = self._fp and self._fp.read(amt)121122 try:123124 if amt:125 return data126127 if not decode_content or not decoder:128 if cache_content:129 self._body = data130131 return data132133 try:134 data = decoder(data)135 except IOError:136 raise HTTPError("Received response with content-encoding: %s, but "137 "failed to decode it." % content_encoding)138139 if cache_content:140 self._body = data141142 return data143144 finally:145146 if self._original_response and self._original_response.isclosed():147 self.release_conn()148149 @staticmethod150 def from_httplib(r, **response_kw):151 """152 Given an httplib.HTTPResponse instance ``r``, return a corresponding153 urllib3.HTTPResponse object.154155 Remaining parameters are passed to the HTTPResponse constructor, along156 with ``original_response=r``.157 """158159 return HTTPResponse(body=r,160 headers=dict(r.getheaders()),161 status=r.status,162 version=r.version,163 reason=r.reason,164 strict=r.strict,165 original_response=r,166 **response_kw)167168 # Backwards-compatibility methods for httplib.HTTPResponse169 def getheaders(self):170 return self.headers171172 def getheader(self, name, default=None):173 return self.headers.get(name, default)