Skip to content
Myr

Merge pull request #1937 from jaraco/master

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Improved decoding support for Response.iter_content and iter_lines

authored by Kenneth Reitz · committed by Kenneth Reitz · parents be2674b, 7b378cb · Browse files · 2 files+32 added−7 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

2 files+32 added−7 removed

  • other:+32 added−7 removed

2 files+32 added−7 removed

modified:requests/models.py+11 added-7 removed
614 unmodified lines
615 request, this avoids reading the content at once into memory for616 large responses. The chunk size is the number of bytes it should617 read into memory. This is not necessarily the length of each item618 returned as decoding can take place.619 """620 if self._content_consumed:621 # simulate reading small chunks of the content622 return iter_slices(self._content, chunk_size)619620 If decode_unicode is True, content will be decoded using the best621 available encoding based on the response.622 """623 def generate():624 try:625 # Special case for urllib3.626 try:
12 unmodified lines
639 yield chunk640641 self._content_consumed = True642644 gen = generate()643 # simulate reading small chunks of the content644 reused_chunks = iter_slices(self._content, chunk_size)645646 stream_chunks = generate()647648 chunks = reused_chunks if self._content_consumed else stream_chunks649650 if decode_unicode:647 gen = stream_decode_response_unicode(gen, self)651 chunks = stream_decode_response_unicode(chunks, self)652649 return gen653 return chunks654655 def iter_lines(self, chunk_size=ITER_CHUNK_SIZE, decode_unicode=None):656 """Iterates over the response data, one line at a time. When657 stream=True is set on the request, this avoids reading the
146 unmodified lines
modified:test_requests.py+21 added
8 unmodified lines
9import pickle10import unittest11import collections1213import io14import requests15import pytest16from requests.adapters import HTTPAdapter17from requests.auth import HTTPDigestAuth
687 unmodified lines
705 r.raw = io706 assert next(iter(r))707 io.close()708709 def test_response_decode_unicode(self):710 """711 When called with decode_unicode, Response.iter_content should always712 return unicode.713 """714 r = requests.Response()715 r._content_consumed = True716 r._content = b'the content'717 r.encoding = 'ascii'718719 chunks = r.iter_content(decode_unicode=True)720 assert all(isinstance(chunk, str) for chunk in chunks)721722 # also for streaming723 r = requests.Response()724 r.raw = io.BytesIO(b'the content')725 r.encoding = 'ascii'726 chunks = r.iter_content(decode_unicode=True)727 assert all(isinstance(chunk, str) for chunk in chunks)728729 def test_request_and_response_are_pickleable(self):730 r = requests.get(httpbin('get'))731732 # verify we can pickle the original request
595 unmodified lines