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
Provenance
- Commit
0db4dab- Tree
9b7c65d- Author
Kenneth Reitz <me@kennethreitz.com>- Committer
Kenneth Reitz <me@kennethreitz.com>- Parent
df66fa7
7 files changed+492 added−173 removed
modified:requests/packages/urllib3/__init__.py+14 added-10 removed
1 """2 urllib3 - Thread-safe connection pooling and re-using.3 """4 5-from connectionpool import (6- connection_from_url,7- get_host,5+__author__ = "Andrey Petrov (andrey.petrov@shazow.net)"6+__license__ = "MIT"7+__version__ = "$Rev$"8+9+10+from .connectionpool import (11 HTTPConnectionPool,12 HTTPSConnectionPool,13+ connection_from_url,14+ get_host,15 make_headers)11-# Possible exceptions12-from connectionpool import (16+17+18+from .exceptions import (19 HTTPError,20 MaxRetryError,21 SSLError,22 TimeoutError)17-from filepost import encode_multipart_formdata23 19-20-__author__ = "Andrey Petrov (andrey.petrov@shazow.net)"21-__license__ = "MIT"22-__version__ = "$Rev$"24+from .poolmanager import PoolManager25+from .response import HTTPResponse26+from .filepost import encode_multipart_formdataadded:requests/packages/urllib3/_collections.py+115 added
1+from collections import MutableMapping, deque2+3+4+__all__ = ['RecentlyUsedContainer']5+6+7+class AccessEntry(object):8+ __slots__ = ('key', 'is_valid')9+10+ def __init__(self, key, is_valid=True):11+ self.key = key12+ self.is_valid = is_valid13+14+15+class 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+ """20+21+ # TODO: Make this threadsafe. _prune_invalidated_entries should be the22+ # only real pain-point for this.23+24+ # 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 = 1028+29+ def __init__(self, maxsize=10):30+ self._maxsize = maxsize31+32+ self._container = {}33+34+ # We use a deque to to store our keys ordered by the last access.35+ self.access_log = deque()36+37+ # 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 = {}41+42+ # Trigger a heap cleanup when we get past this size43+ self.access_log_limit = maxsize * self.CLEANUP_FACTOR44+45+ 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 = False51+52+ new_entry = AccessEntry(key)53+54+ self.access_lookup[key] = new_entry55+ self.access_log.appendleft(new_entry)56+57+ 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()61+62+ if not p.is_valid:63+ continue # Invalidated entry, skip64+65+ del self._container[p.key]66+ del self.access_lookup[p.key]67+ num -= 168+69+ 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)72+73+ def _get_ordered_access_keys(self):74+ # Used for testing75+ return [e.key for e in self.access_log if e.is_valid]76+77+ def __getitem__(self, key):78+ item = self._container.get(key)79+80+ if not item:81+ return82+83+ # Insert new entry with new high priority, also implicitly invalidates84+ # the old entry.85+ self._push_entry(key)86+87+ 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()91+92+ return item93+94+ def __setitem__(self, key, item):95+ # Add item to our container and access log96+ self._container[key] = item97+ self._push_entry(key)98+99+ # Discard invalid and excess entries100+ self._prune_entries(len(self._container) - self._maxsize)101+102+103+ def __delitem__(self, key):104+ self._invalidate_entry(key)105+ del self._container[key]106+ del self._access_lookup[key]107+108+ def __len__(self):109+ return len(self.access_log)110+111+ def __iter__(self):112+ return self._container.__iter__()113+114+ def __contains__(self, key):115+ return self._container.__contains__(key)modified:requests/packages/urllib3/connectionpool.py+88 added-156 removed
1-import gzip2-import zlib1 import logging2 import socket3 4 6 unmodified lines11 12 try:13 import ssl14 BaseSSLError = ssl.SSLError17-except ImportError, e:15+except ImportError:16 ssl = None17 BaseSSLError = None18 21-try:22- from cStringIO import StringIO23-except ImportError, e:24- from StringIO import StringIO19 20+from .filepost import encode_multipart_formdata21+from .response import HTTPResponse22+from .exceptions import (23+ SSLError,24+ MaxRetryError,25+ TimeoutError,26+ HostChangedError,27+ EmptyPoolError)28 27-from filepost import encode_multipart_formdata29 29-30 log = logging.getLogger(__name__)31 32 33-## Exceptions33+## Connection objects (extension of httplib)34 35-class HTTPError(Exception):36- "Base exception used by this module."37- pass38-39-40-class SSLError(Exception):41- "Raised when SSL certificate fails in an HTTPS connection."42- pass43-44-45-class MaxRetryError(HTTPError):46- "Raised when the maximum number of retries is exceeded."47- pass48-49-50-class TimeoutError(HTTPError):51- "Raised when a socket timeout occurs."52- pass53-54-55-class HostChangedError(HTTPError):56- "Raised when an existing pool gets a request for a foreign host."57- pass58-59-60-## Response objects61-62-class HTTPResponse(object):63- """64- HTTP Response container.65-66- Similar to httplib's HTTPResponse but the data is pre-loaded.67- """68-69- 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 = strict77-78- @staticmethod79- def from_httplib(r, block=True):80- """81- Given an httplib.HTTPResponse instance, return a corresponding82- urllib3.HTTPResponse object.83-84- NOTE: This method will perform r.read() which will have side effects85- on the original http.HTTPResponse object.86- """87-88- 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.")94-95- 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_data106-107- 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 = None113-114- 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)120-121- resp._raw = r122- return resp123-124- # Backwards-compatibility methods for httplib.HTTPResponse125- def getheaders(self):126- return self.headers127-128- def getheader(self, name, default=None):129- return self.headers.get(name, default)130-131-132-## Connection objects133-35 class VerifiedHTTPSConnection(HTTPSConnection):36 """37 Based on httplib.HTTPSConnection but wraps the socket with38 SSL certification.39 """40 41+ def __init__(self):42+ HTTPSConnection.__init__()43+ self.cert_reqs = None44+ self.ca_certs = None45+140- 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_REQUIRED16 unmodified lines68 69 70 ## Pool objects71 166-class HTTPConnectionPool(object):72+class ConnectionPool(object):73+ pass74+75+76+class HTTPConnectionPool(ConnectionPool):77 """78 Thread-safe connection pool for one host.79 80 host43 unmodified lines124 self.block = block125 self.headers = headers or {}126 127 # 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)130 131+ # These are mostly for testing and debugging purposes.132 self.num_connections = 0133 self.num_requests = 0134 135 def _new_conn(self):16 unmodified lines152 153 # 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()158 248- 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 then164 165 return conn or self._new_conn()166 5 unmodified lines172 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)180 181+ 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 += 1187+188+ conn.request(method, url, **httplib_request_kw)189+ conn.sock.settimeout(self.timeout)190+ httplib_response = conn.getresponse()191+192+ 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))196+197+ return httplib_response198+199+200 def is_same_host(self, url):201 return (url.startswith('/') or202 get_host(url) == (self.scheme, self.host, self.port))203 204 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.209 210 method20 unmodified lines231 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.235+236+ 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.240+241+ Additional parameters are passed to242+ ``HTTPResponse.from_httplib(r, **response_kw)``243 """302- if headers == None:244+ if headers is None:245 headers = self.headers246 247 if retries < 0:248 raise MaxRetryError("Max retries exceeded for url: %s" % url)8 unmodified lines257 "open a foreign host: %s" % (host, url))258 259 try:260 # Request a connection from the queue319- conn = self._get_conn()261+ conn = self._get_conn(timeout=pool_timeout)262 321- # 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)266 330- # 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)272 335- # 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())275 276 except (SocketTimeout, Empty), e:277 # Timed out either by socket or queue278 raise TimeoutError("Request timed out after %f seconds" %21 unmodified lines300 301 return response302 303 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).307 308 Supports an optional ``fields`` dictionary parameter key/value strings.1 unmodified line310 """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)315 316 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 lines342 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 line353 headers = headers or {}354 headers.update({'Content-Type': content_type})355 356 return self.urlopen('POST', url, body, headers=headers,417- retries=retries, redirect=redirect)357+ retries=retries, redirect=redirect, **response_kw)358 359 360 class HTTPSConnectionPool(HTTPConnectionPool):361 """1 unmodified line363 """364 365 scheme = 'https'366 427- 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):372 373+ 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_certs380 443- # Fill the queue up so that doing get() on it will block properly444- [self.pool.put(None) for i in xrange(maxsize)]445-446- self.num_connections = 0447- self.num_requests = 0448-381 def _new_conn(self):382 """383 Return a fresh HTTPSConnection.384 """73 unmodified lines458 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, port17 unmodified linesadded:requests/packages/urllib3/exceptions.py+29 added
1+## Exceptions2+3+class HTTPError(Exception):4+ "Base exception used by this module."5+ pass6+7+8+class SSLError(Exception):9+ "Raised when SSL certificate fails in an HTTPS connection."10+ pass11+12+13+class MaxRetryError(HTTPError):14+ "Raised when the maximum number of retries is exceeded."15+ pass16+17+18+class TimeoutError(HTTPError):19+ "Raised when a socket timeout occurs."20+ pass21+22+23+class HostChangedError(HTTPError):24+ "Raised when an existing pool gets a request for a foreign host."25+ pass26+27+class EmptyPoolError(HTTPError):28+ "Raised when a pool runs out of connections and no more are allowed."29+ passmodified:requests/packages/urllib3/filepost.py+9 added-7 removed
1 import codecs2 import mimetools3 import mimetypes4+5 try:6 from cStringIO import StringIO6-except:7- from StringIO import StringIO7+except ImportError:8+ from StringIO import StringIO # pylint: disable-msg=W04049 10 11 writer = codecs.lookup('utf-8')[3]12 1 unmodified line14 def get_content_type(filename):15 return mimetypes.guess_type(filename)[0] or 'application/octet-stream'16 17 17-def encode_multipart_formdata(fields):18+def encode_multipart_formdata(fields, boundary=None):19 body = StringIO()20+ if boundary is None:19- BOUNDARY = mimetools.choose_boundary()21+ boundary = mimetools.choose_boundary()22 23 for fieldname, value in fields.iteritems():22- body.write('--%s\r\n' % (BOUNDARY))24+ body.write('--%s\r\n' % (boundary))25 26 if isinstance(value, tuple):27 filename, data = value28 writer(body).write('Content-Disposition: form-data; name="%s"; '15 unmodified lines44 body.write(data)45 46 body.write('\r\n')47 46- body.write('--%s--\r\n' % (BOUNDARY))48+ body.write('--%s--\r\n' % (boundary))49 48- content_type = 'multipart/form-data; boundary=%s' % BOUNDARY50+ content_type = 'multipart/form-data; boundary=%s' % boundary51 52 return body.getvalue(), content_typeadded:requests/packages/urllib3/poolmanager.py+64 added
1+from ._collections import RecentlyUsedContainer2+from .connectionpool import HTTPConnectionPool, HTTPSConnectionPool, get_host3+4+5+pool_classes_by_scheme = {6+ 'http': HTTPConnectionPool,7+ 'https': HTTPSConnectionPool,8+}9+10+port_by_scheme = {11+ 'http': 80,12+ 'https': 433,13+}14+15+16+class PoolManager(object):17+ """18+ Allows for arbitrary requests while transparently keeping track of19+ necessary connection pools for you.20+21+ num_pools22+ Number of connection pools to cache before discarding the least recently23+ used pool.24+25+ Additional parameters are used to create fresh ConnectionPool instances.26+27+ """28+29+ # TODO: Make sure there are no memory leaks here.30+31+ def __init__(self, num_pools=10, **connection_pool_kw):32+ self.connection_pool_kw = connection_pool_kw33+34+ self.pools = RecentlyUsedContainer(num_pools)35+ self.recently_used_pools = []36+37+ 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)44+45+ # 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))48+49+ pool = self.pools.get(pool_key)50+ if pool:51+ return pool52+53+ # 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)56+57+ self.pools[pool_key] = pool58+59+ return pool60+61+ 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
1+import gzip2+import logging3+import zlib4+5+6+try:7+ from cStringIO import StringIO8+except ImportError:9+ from StringIO import StringIO # pylint: disable-msg=W040410+11+12+from .exceptions import HTTPError13+14+15+log = logging.getLogger(__name__)16+17+18+def decode_gzip(data):19+ gzipper = gzip.GzipFile(fileobj=StringIO(data))20+ return gzipper.read()21+22+23+def decode_deflate(data):24+ try:25+ return zlib.decompress(data)26+ except zlib.error:27+ return zlib.decompress(data, -zlib.MAX_WBITS)28+29+30+class HTTPResponse(object):31+ """32+ HTTP Response container.33+34+ Backwards-compatible to httplib's HTTPResponse but the response ``body`` is35+ loaded and decoded on-demand when the ``data`` property is accessed.36+37+ Extra parameters for behaviour not present in httplib.HTTPResponse:38+39+ preload_content40+ If True, the response's body will be preloaded during construction.41+42+ 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.46+47+ 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+ """52+53+ CONTENT_DECODERS = {54+ 'gzip': decode_gzip,55+ 'deflate': decode_deflate,56+ }57+58+ 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 = strict66+67+ self._decode_content = decode_content68+ self._body = None69+ self._fp = None70+ self._original_response = original_response71+72+ self._pool = pool73+ self._connection = connection74+75+ if hasattr(body, 'read'):76+ self._fp = body77+78+ if preload_content:79+ self._body = self.read(decode_content=decode_content)80+81+ def release_conn(self):82+ if not self._pool or not self._connection:83+ return84+85+ self._pool._put_conn(self._connection)86+87+ @property88+ def data(self):89+ # For backwords-compat with earlier urllib3 0.4 and earlier.90+ if self._body:91+ return self._body92+93+ if self._fp:94+ return self.read(decode_content=self._decode_content,95+ cache_content=True)96+97+ def read(self, amt=None, decode_content=True, cache_content=False):98+ """99+ Similar to ``httplib.HTTPResponse.read(amt=None)``.100+101+ 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.105+106+ decode_content107+ If True, will attempt to decode the body based on the108+ 'content-encoding' header. (Overridden if ``amt`` is set.)109+110+ 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)119+120+ data = self._fp and self._fp.read(amt)121+122+ try:123+124+ if amt:125+ return data126+127+ if not decode_content or not decoder:128+ if cache_content:129+ self._body = data130+131+ return data132+133+ 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)138+139+ if cache_content:140+ self._body = data141+142+ return data143+144+ finally:145+146+ if self._original_response and self._original_response.isclosed():147+ self.release_conn()148+149+ @staticmethod150+ def from_httplib(r, **response_kw):151+ """152+ Given an httplib.HTTPResponse instance ``r``, return a corresponding153+ urllib3.HTTPResponse object.154+155+ Remaining parameters are passed to the HTTPResponse constructor, along156+ with ``original_response=r``.157+ """158+159+ 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)167+168+ # Backwards-compatibility methods for httplib.HTTPResponse169+ def getheaders(self):170+ return self.headers171+172+ def getheader(self, name, default=None):173+ return self.headers.get(name, default)