Merge remote-tracking branch 'origin/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 aafca7a, a527ecf · Browse files · 9 files·+85 added−76 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
9 files+85 added−76 removed
- other:+85 added−76 removed
Provenance
- Commit
636476e- Tree
f3c0f91- Author
Kenneth Reitz <me@kennethreitz.com>- Committer
Kenneth Reitz <me@kennethreitz.com>- Parent 1
aafca7a- Parent 2
a527ecf
9 files changed+85 added−76 removed
modified:docs/api.rst+17 added-3 removed
163 unmodified lines164 configuring logging.165 166 ::167 168- # Verbosity should now be configured with logging169- my_config = {'verbose': sys.stderr}170- requests.get('http://httpbin.org/headers', config=my_config) # bad!168+ import requests169+ import logging170 171+ # these two lines enable debugging at httplib level (requests->urllib3->httplib)172+ # you will see the REQUEST, including HEADERS and DATA, and RESPONSE with HEADERS but without DATA.173+ # the only thing missing will be the response.body which is not logged.174+ import httplib175+ httplib.HTTPConnection.debuglevel = 1176+ 177+ logging.basicConfig() # you need to initialize logging, otherwise you will not see anything from requests178+ logging.getLogger().setLevel(logging.DEBUG)179+ requests_log = logging.getLogger("requests.packages.urllib3")180+ requests_log.setLevel(logging.DEBUG)181+ requests_log.propagate = True182+ 183+ requests.get('http://httpbin.org/headers')184 185+186+187 Licensing188 ~~~~~~~~~189 190 One key difference that has nothing to do with the API is a change in the7 unmodified linesmodified: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/auth.py+3 added-1 removed
6 unmodified lines7 This module contains the authentication handlers for Requests.8 """9 10 import os11+import re12 import time13 import hashlib14 import logging15 135 unmodified lines151 152 if 'digest' in s_auth.lower() and num_401_calls < 2:153 154 setattr(self, 'num_401_calls', num_401_calls + 1)155+ pat = re.compile(r'digest ', flags=re.IGNORECASE)154- self.chal = parse_dict_header(s_auth.replace('Digest ', ''))156+ self.chal = parse_dict_header(pat.sub('', s_auth))157 158 # Consume content and release the original connection159 # to allow our new request to reuse the same one.160 r.content17 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:.gitignore+2 added
5 unmodified lines6 pylint.txt7 toy.py8 violations.pyflakes.txt9 cover/10+build/11 docs/_build12 requests.egg-info/13 *.pyc14 *.swp15+*.egg16 env/17 18 .workon19 3 unmodified linesmodified:setup.py+1 added
37 unmodified lines38 package_data={'': ['LICENSE', 'NOTICE'], 'requests': ['*.pem']},39 package_dir={'requests': 'requests'},40 include_package_data=True,41 install_requires=requires,42+ setup_requires=['sphinx'],43 license=open('LICENSE').read(),44 zip_safe=False,45 classifiers=(46 'Development Status :: 5 - Production/Stable',13 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