Merge pull request #1299 from schlamar/fix-decompression
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Use streaming decompression feature of urllib3.
authored by Kenneth Reitz · committed by Kenneth Reitz · parents 9df4501, 4c3432b · Browse files · 5 files·+62 added−72 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
5 files+62 added−72 removed
- other:+62 added−72 removed
Provenance
- Commit
967cfbe- Tree
af0080e- Author
Kenneth Reitz <me@kennethreitz.com>- Committer
Kenneth Reitz <me@kennethreitz.com>- Parent 1
9df4501- Parent 2
4c3432b
5 files changed+62 added−72 removed
modified:requests/packages/urllib3/filepost.py+1 added-1 removed
91 unmodified lines92 body.write(b'\r\n')93 94 body.write(b('--%s--\r\n' % (boundary)))95 96- content_type = b('multipart/form-data; boundary=%s' % boundary)96+ content_type = str('multipart/form-data; boundary=%s' % boundary)97 98 return body.getvalue(), content_typemodified:requests/packages/urllib3/response.py+53 added-26 removed
2 unmodified lines3 #4 # This module is part of urllib3 and is released under5 # the MIT License: http://www.opensource.org/licenses/mit-license.php6 7-import gzip7+8 import logging9 import zlib10 11-from io import BytesIO12-11 from .exceptions import DecodeError14-from .packages.six import string_types as basestring12+from .packages.six import string_types as basestring, binary_type13 14 15 log = logging.getLogger(__name__)16 17 20-def decode_gzip(data):21- gzipper = gzip.GzipFile(fileobj=BytesIO(data))22- return gzipper.read()18+class DeflateDecoder(object):19 20+ def __init__(self):21+ self._first_try = True22+ self._data = binary_type()23+ self._obj = zlib.decompressobj()24 25-def decode_deflate(data):26- try:27- return zlib.decompress(data)28- except zlib.error:29- return zlib.decompress(data, -zlib.MAX_WBITS)25+ def __getattr__(self, name):26+ return getattr(self._obj, name)27 28+ def decompress(self, data):29+ if not self._first_try:30+ return self._obj.decompress(data)31 32+ self._data += data33+ try:34+ return self._obj.decompress(data)35+ except zlib.error:36+ self._first_try = False37+ self._obj = zlib.decompressobj(-zlib.MAX_WBITS)38+ try:39+ return self.decompress(self._data)40+ finally:41+ self._data = None42+43+44+def _get_decoder(mode):45+ if mode == 'gzip':46+ return zlib.decompressobj(16 + zlib.MAX_WBITS)47+48+ return DeflateDecoder()49+50+51 class HTTPResponse(object):52 """53 HTTP Response container.54 15 unmodified lines70 object, it's convenient to include the original for debug purposes. It's71 otherwise unused.72 """73 55- CONTENT_DECODERS = {56- 'gzip': decode_gzip,57- 'deflate': decode_deflate,58- }74+ CONTENT_DECODERS = ['gzip', 'deflate']75 76 def __init__(self, body='', headers=None, status=0, version=0, reason=None,77 strict=0, preload_content=True, decode_content=True,78 original_response=None, pool=None, connection=None):1 unmodified line80 self.status = status81 self.version = version82 self.reason = reason83 self.strict = strict84+ self.decode_content = decode_content85 69- self._decode_content = decode_content86+ self._decoder = None87 self._body = body if body and isinstance(body, basestring) else None88 self._fp = None89 self._original_response = original_response90 40 unmodified lines131 Similar to :meth:`httplib.HTTPResponse.read`, but with two additional132 parameters: ``decode_content`` and ``cache_content``.133 134 :param amt:118- How much of the content to read. If specified, decoding and caching119- is skipped because we can't decode partial content nor does it make120- sense to cache partial content as the full response.135+ How much of the content to read. If specified, caching is skipped136+ because it doesn't make sense to cache partial content as the full137+ response.138 139 :param decode_content:140 If True, will attempt to decode the body based on the124- 'content-encoding' header. (Overridden if ``amt`` is set.)141+ 'content-encoding' header.142 143 :param cache_content:144 If True, will save the returned data such that the same result is145 returned despite of the state of the underlying file object. This3 unmodified lines149 """150 # Note: content-encoding value should be case-insensitive, per RFC 2616151 # Section 3.5152 content_encoding = self.headers.get('content-encoding', '').lower()136- decoder = self.CONTENT_DECODERS.get(content_encoding)153+ if self._decoder is None:154+ if content_encoding in self.CONTENT_DECODERS:155+ self._decoder = _get_decoder(content_encoding)156 if decode_content is None:138- decode_content = self._decode_content157+ decode_content = self.decode_content158 159 if self._fp is None:160 return161 162+ flush_decoder = False163+164 try:165 if amt is None:166 # cStringIO doesn't like amt=None167 data = self._fp.read()168+ flush_decoder = True169 else:170+ cache_content = False171 data = self._fp.read(amt)172 if amt != 0 and not data: # Platform-specific: Buggy versions of Python.173 # Close the connection when no data is returned174 #2 unmodified lines177 # December 15, 2012 (http://bugs.python.org/issue16298) do not178 # properly close the connection in all cases. There is no harm179 # in redundantly calling close.180 self._fp.close()158- return data181+ flush_decoder = True182 183 try:161- if decode_content and decoder:162- data = decoder(data)184+ if decode_content and self._decoder:185+ data = self._decoder.decompress(data)186 except (IOError, zlib.error):187 raise DecodeError("Received response with content-encoding: %s, but "188 "failed to decode it." % content_encoding)189 190+ if flush_decoder and self._decoder:191+ buf = self._decoder.decompress(binary_type())192+ data += buf + self._decoder.flush()193+194 if cache_content:195 self._body = data196 197 return data44 unmodified linesmodified:requests/models.py+3 added-3 removed
18 unmodified lines19 from .cookies import cookiejar_from_dict, get_cookie_header20 from .packages.urllib3.filepost import encode_multipart_formdata21 from .exceptions import HTTPError, RequestException, MissingSchema, InvalidURL22 from .utils import (23- stream_untransfer, guess_filename, get_auth_from_url, requote_uri,23+ guess_filename, get_auth_from_url, requote_uri,24 stream_decode_response_unicode, to_key_val_list, parse_header_links,25 iter_slices, guess_json_utf, super_len)26 from .compat import (27 cookielib, urlparse, urlunparse, urlsplit, urlencode, str, bytes, StringIO,499 unmodified lines527 return iter_slices(self._content, chunk_size)528 529 def generate():530 while 1:531- chunk = self.raw.read(chunk_size)531+ chunk = self.raw.read(chunk_size, decode_content=True)532 if not chunk:533 break534 yield chunk535 self._content_consumed = True536 537- gen = stream_untransfer(generate(), self)537+ gen = generate()538 539 if decode_unicode:540 gen = stream_decode_response_unicode(gen, self)541 135 unmodified linesmodified:requests/utils.py-42 removed
344 unmodified lines345 except TypeError:346 return r.content347 348 349-def stream_decompress(iterator, mode='gzip'):350- """Stream decodes an iterator over compressed data351-352- :param iterator: An iterator over compressed data353- :param mode: 'gzip' or 'deflate'354- :return: An iterator over decompressed data355- """356-357- if mode not in ['gzip', 'deflate']:358- raise ValueError('stream_decompress mode must be gzip or deflate')359-360- zlib_mode = 16 + zlib.MAX_WBITS if mode == 'gzip' else -zlib.MAX_WBITS361- dec = zlib.decompressobj(zlib_mode)362- try:363- for chunk in iterator:364- rv = dec.decompress(chunk)365- if rv:366- yield rv367- except zlib.error:368- # If there was an error decompressing, just return the raw chunk369- yield chunk370- # Continue to return the rest of the raw data371- for chunk in iterator:372- yield chunk373- else:374- # Make sure everything has been returned from the decompression object375- buf = dec.decompress(bytes())376- rv = buf + dec.flush()377- if rv:378- yield rv379-380-381-def stream_untransfer(gen, resp):382- ce = resp.headers.get('content-encoding', '').lower()383- if 'gzip' in ce:384- gen = stream_decompress(gen, mode='gzip')385- elif 'deflate' in ce:386- gen = stream_decompress(gen, mode='deflate')387-388- return gen389-390-349 # The unreserved URI characters (RFC 3986)350 UNRESERVED_SET = frozenset(351 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"352 + "0123456789-._~")197 unmodified linesmodified:test_requests.py+5 added
378 unmodified lines379 380 def test_response_is_iterable(self):381 r = requests.Response()382 io = StringIO.StringIO('abc')383+ read_ = io.read384+385+ def read_mock(amt, decode_content=None):386+ return read_(amt)387+ setattr(io, 'read', read_mock)388 r.raw = io389 self.assertTrue(next(iter(r)))390 io.close()391 31 unmodified lines