Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add readinto to StreamingBody #2746

Open
wants to merge 1 commit into
base: develop
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions botocore/response.py
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,21 @@ def read(self, amt=None):
def readlines(self):
return self._raw_stream.readlines()

def readinto(self, b):
try:
amount_read = self._raw_stream.readinto(b)
except URLLib3ReadTimeoutError as e:
# TODO: the url will be None as urllib3 isn't setting it yet
raise ReadTimeoutError(endpoint_url=e.url, error=e)
except URLLib3ProtocolError as e:
raise ResponseStreamingError(error=e)
self._amount_read += amount_read
if amount_read == 0:
# If the server sends empty contents then we know we need to verify
# the content length.
self._verify_content_length()
return amount_read

def __iter__(self):
"""Return an iterator to yield 1k chunks from the raw stream."""
return self.iter_chunks(self._DEFAULT_CHUNK_SIZE)
Expand Down
18 changes: 18 additions & 0 deletions tests/unit/test_response.py
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,24 @@ def test_streaming_body_readlines(self):
chunks = [b'1234567890\n', b'1234567890\n', b'12345']
self.assertEqual(stream.readlines(), chunks)

def test_streaming_body_readinto(self):
body = BytesIO(b'123456789')
stream = response.StreamingBody(body, content_length=9)
chunk = bytearray(b'\x00\x00\x00\x00\x00')
self.assertEqual(5, stream.readinto(chunk))
self.assertEqual(chunk, bytearray(b'\x31\x32\x33\x34\x35'))
self.assertEqual(4, stream.readinto(chunk))
self.assertEqual(chunk, bytearray(b'\x36\x37\x38\x39\x35'))

def test_streaming_body_readinto_with_invalid_length(self):
body = BytesIO(b'12')
stream = response.StreamingBody(body, content_length=9)
chunk = bytearray(b'\xDE\xAD\xBE\xEF')
self.assertEqual(2, stream.readinto(chunk))
self.assertEqual(chunk, bytearray(b'\x31\x32\xBE\xEF'))
with self.assertRaises(IncompleteReadError):
stream.readinto(chunk)

def test_streaming_body_tell(self):
body = BytesIO(b'1234567890')
stream = response.StreamingBody(body, content_length=10)
Expand Down