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

Optimize reading from S3 #322

Merged
merged 3 commits into from
May 29, 2019
Merged
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
19 changes: 12 additions & 7 deletions smart_open/s3.py
Original file line number Diff line number Diff line change
Expand Up @@ -147,12 +147,9 @@ def read(self, size=-1):
class SeekableRawReader(object):
"""Read an S3 object."""

def __init__(self, s3_object):
def __init__(self, s3_object, content_length):
self._object = s3_object
try:
self._content_length = self._object.content_length
except botocore.client.ClientError:
raise ValueError('the s3 key %r does not exist, or is forbidden for access' % s3_object.key)
self._content_length = content_length
self.seek(0)

def seek(self, position):
Expand Down Expand Up @@ -339,8 +336,16 @@ def __init__(self, bucket, key, buffer_size=DEFAULT_BUFFER_SIZE,
resource_kwargs = {}
s3 = session.resource('s3', **resource_kwargs)
self._object = s3.Object(bucket, key)
self._raw_reader = SeekableRawReader(self._object)
self._content_length = self._object.content_length

try:
self._content_length = self._object.content_length
except botocore.client.ClientError:
raise ValueError(
'%r does not exist in the bucket %r, '
'or is forbidden for access' % (key, bucket)
)

self._raw_reader = SeekableRawReader(self._object, self._content_length)
self._current_pos = 0
self._buffer = smart_open.bytebuffer.ByteBuffer(buffer_size)
self._eof = False
Expand Down
2 changes: 2 additions & 0 deletions smart_open/tests/test_s3.py
Original file line number Diff line number Diff line change
Expand Up @@ -386,6 +386,8 @@ def test_nonexisting_bucket(self):
fout.write(expected)

def test_read_nonexisting_key(self):
create_bucket_and_key()
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What was happening before this change? Testing for a missing bucket?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nonexisting key in an existing bucket.

The test started failing once we moved the content_length calls around. It's probably tripping over some moto oddity


with self.assertRaises(ValueError):
with smart_open.s3.open(BUCKET_NAME, 'my_nonexisting_key', 'rb') as fin:
fin.read()
Expand Down