Merge remote-tracking branch 'origin/develop' into develop
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 a69cf7e, 6497d11 · Browse files · 4 files·+35 added−18 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
4 files+35 added−18 removed
- tests:+18 added−0 removed
- other:+17 added−18 removed
Provenance
- Commit
c8f166f- Tree
06af1a6- Author
Kenneth Reitz <me@kennethreitz.com>- Committer
Kenneth Reitz <me@kennethreitz.com>- Parent 1
a69cf7e- Parent 2
6497d11
4 files changed+35 added−18 removed
modified:docs/user/advanced.rst+8 added-14 removed
114 unmodified lines115 116 Body Content Workflow117 ---------------------118 119-By default, when you make a request, the body of the response isn't downloaded immediately. The response headers are downloaded when you make a request, but the content isn't downloaded until you access the :class:`Response.content` attribute.119+By default, when you make a request, the body of the response is downloaded immediately. You can override this behavior and defer downloading the response body until you access the :class:`Response.content` attribute with the ``prefetch`` parameter::120 121-Let's walk through it::122-121 tarball_url = 'https://github.com/kennethreitz/requests/tarball/master'124- r = requests.get(tarball_url)122+ r = requests.get(tarball_url, prefetch=False)123 126-The request has been made, but the connection is still open. The response body has not been downloaded yet.124+At this point only the response headers have been downloaded and the connection remains open, hence allowing us to make content retrieval conditional::125 128-::126+ if int(r.headers['content-length']) < TOO_LONG:127+ content = r.content128+ ...129 130- r.content130+You can further control the workflow by use of the :class:`Response.iter_content` and :class:`Response.iter_lines` methods, or reading from the underlying urllib3 :class:`urllib3.HTTPResponse` at :class:`Response.raw`.131 132-The content has been downloaded and cached.132+Note that in versions prior to 0.13.6 the ``prefetch`` default was set to ``False``.133 134-You can override this default behavior with the ``prefetch`` parameter::135-136- r = requests.get(tarball_url, prefetch=True)137- # Blocks until all of request body has been downloaded.138-139-134 Configuring Requests135 --------------------136 137 Sometimes you may want to configure a request to customize its behavior. To do424 unmodified linesmodified:requests/models.py+3 added-4 removed
29 unmodified lines30 URLRequired, SSLError, MissingSchema, InvalidSchema, InvalidURL)31 from .utils import (32 get_encoding_from_headers, stream_untransfer, guess_filename, requote_uri,33 stream_decode_response_unicode, get_netrc_auth, get_environ_proxies,34- to_key_val_list, DEFAULT_CA_BUNDLE_PATH, parse_header_links)34+ to_key_val_list, DEFAULT_CA_BUNDLE_PATH, parse_header_links, iter_slices)35 from .compat import (36 cookielib, urlparse, urlunparse, urljoin, urlsplit, urlencode, str, bytes,37 StringIO, is_py2, chardet, json, builtin_str, numeric_types)38 690 unmodified lines729 of bytes it should read into memory. This is not necessarily the730 length of each item returned as decoding can take place.731 """732 if self._content_consumed:733- raise RuntimeError(734- 'The content for this response was already consumed'735- )733+ # simulate reading small chunks of the content734+ return iter_slices(self._content, chunk_size)735 736 def generate():737 while 1:738 chunk = self.raw.read(chunk_size)146 unmodified linesmodified:requests/utils.py+6 added
358 unmodified lines359 rv = decoder.decode('', final=True)360 if rv:361 yield rv362 363+def iter_slices(string, slice_length):364+ """Iterate over slices of a string."""365+ pos = 0366+ while pos < len(string):367+ yield string[pos:pos+slice_length]368+ pos += slice_length369 370 def get_unicode_from_response(r):371 """Returns the requested content back in unicode.372 187 unmodified linesmodified:tests/test_requests.py+18 added
922 unmodified lines923 924 joined = lines[0] + '\n' + lines[1] + '\r\n' + lines[2]925 self.assertEqual(joined, quote)926 927+ def test_permissive_iter_content(self):928+ """Test that iter_content and iter_lines work even after the body has been fetched."""929+ r = get(httpbin('stream', '10'), prefetch=True)930+ assert r._content_consumed931+ # iter_lines should still work without crashing932+ self.assertEqual(len(list(r.iter_lines())), 10)933+934+ # iter_content should return a one-item iterator over the whole content935+ iter_content_list = list(r.iter_content(chunk_size=1))936+ self.assertTrue(all(len(item) == 1 for item in iter_content_list))937+ # when joined, it should be exactly the original content938+ self.assertEqual(bytes().join(iter_content_list), r.content)939+940+ # test different chunk sizes:941+ for chunk_size in range(2, 20):942+ self.assertEqual(bytes().join(r.iter_content(chunk_size=chunk_size)), r.content)943+944+945 # def test_safe_mode(self):946 947 # safe = requests.session(config=dict(safe_mode=True))948 196 unmodified lines