Skip to content
Myr

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

9 files+85 added−76 removed

modified:docs/api.rst+17 added-3 removed
163 unmodified lines
164 configuring logging.165166 ::167168 # 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 logging170171 # 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')184185186187Licensing188~~~~~~~~~189190One key difference that has nothing to do with the API is a change in the
7 unmodified lines
modified:requests/packages/urllib3/filepost.py+1 added-1 removed
91 unmodified lines
92 body.write(b'\r\n')9394 body.write(b('--%s--\r\n' % (boundary)))9596 content_type = b('multipart/form-data; boundary=%s' % boundary)96 content_type = str('multipart/form-data; boundary=%s' % boundary)9798 return body.getvalue(), content_type
modified:requests/packages/urllib3/response.py+53 added-26 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 gzip78import logging9import zlib1011from io import BytesIO1211from .exceptions import DecodeError14from .packages.six import string_types as basestring12from .packages.six import string_types as basestring, binary_type131415log = logging.getLogger(__name__)161720def decode_gzip(data):21 gzipper = gzip.GzipFile(fileobj=BytesIO(data))22 return gzipper.read()18class DeflateDecoder(object):1920 def __init__(self):21 self._first_try = True22 self._data = binary_type()23 self._obj = zlib.decompressobj()2425def 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)2728 def decompress(self, data):29 if not self._first_try:30 return self._obj.decompress(data)3132 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 = None424344def _get_decoder(mode):45 if mode == 'gzip':46 return zlib.decompressobj(16 + zlib.MAX_WBITS)4748 return DeflateDecoder()495051class HTTPResponse(object):52 """53 HTTP Response container.54
15 unmodified lines
70 object, it's convenient to include the original for debug purposes. It's71 otherwise unused.72 """7355 CONTENT_DECODERS = {56 'gzip': decode_gzip,57 'deflate': decode_deflate,58 }74 CONTENT_DECODERS = ['gzip', 'deflate']7576 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 line
80 self.status = status81 self.version = version82 self.reason = reason83 self.strict = strict84 self.decode_content = decode_content8569 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 lines
131 Similar to :meth:`httplib.HTTPResponse.read`, but with two additional132 parameters: ``decode_content`` and ``cache_content``.133134 :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.138139 :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.142143 :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. This
3 unmodified lines
149 """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_content158159 if self._fp is None:160 return161162 flush_decoder = False163164 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 lines
177 # 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 = True182183 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)189190 if flush_decoder and self._decoder:191 buf = self._decoder.decompress(binary_type())192 data += buf + self._decoder.flush()193194 if cache_content:195 self._body = data196197 return data
44 unmodified lines
modified:requests/auth.py+3 added-1 removed
6 unmodified lines
7This module contains the authentication handlers for Requests.8"""910import os11import re12import time13import hashlib14import logging15
135 unmodified lines
151152 if 'digest' in s_auth.lower() and num_401_calls < 2:153154 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))157158 # Consume content and release the original connection159 # to allow our new request to reuse the same one.160 r.content
17 unmodified lines
modified:requests/models.py+3 added-3 removed
18 unmodified lines
19from .cookies import cookiejar_from_dict, get_cookie_header20from .packages.urllib3.filepost import encode_multipart_formdata21from .exceptions import HTTPError, RequestException, MissingSchema, InvalidURL22from .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)26from .compat import (27 cookielib, urlparse, urlunparse, urlsplit, urlencode, str, bytes, StringIO,
499 unmodified lines
527 return iter_slices(self._content, chunk_size)528529 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 = True536537 gen = stream_untransfer(generate(), self)537 gen = generate()538539 if decode_unicode:540 gen = stream_decode_response_unicode(gen, self)541
135 unmodified lines
modified:requests/utils.py-42 removed
344 unmodified lines
345 except TypeError:346 return r.content347348349def stream_decompress(iterator, mode='gzip'):350 """Stream decodes an iterator over compressed data351352 :param iterator: An iterator over compressed data353 :param mode: 'gzip' or 'deflate'354 :return: An iterator over decompressed data355 """356357 if mode not in ['gzip', 'deflate']:358 raise ValueError('stream_decompress mode must be gzip or deflate')359360 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 rv379380381def 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')387388 return gen389390349# The unreserved URI characters (RFC 3986)350UNRESERVED_SET = frozenset(351 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"352 + "0123456789-._~")
197 unmodified lines
modified:.gitignore+2 added
5 unmodified lines
6pylint.txt7toy.py8violations.pyflakes.txt9cover/10build/11docs/_build12requests.egg-info/13*.pyc14*.swp15*.egg16env/1718.workon19
3 unmodified lines
modified:setup.py+1 added
37 unmodified lines
38 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 lines
modified:test_requests.py+5 added
378 unmodified lines
379380 def test_response_is_iterable(self):381 r = requests.Response()382 io = StringIO.StringIO('abc')383 read_ = io.read384385 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