Skip to content

Commit 2c51751

Browse files
committed
Merge branch 'morosi-feat' into 'master'
Add S3.get_object/get_body methods See merge request it/e3-aws!106
2 parents 62bd5a9 + dd5f1a2 commit 2c51751

File tree

1 file changed

+29
-8
lines changed

1 file changed

+29
-8
lines changed

src/e3/aws/s3/__init__.py

Lines changed: 29 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88
import boto3
99

1010
if TYPE_CHECKING:
11-
from typing import Any, BinaryIO
11+
from typing import Any, BinaryIO, IO
1212
from collections.abc import Iterable, Iterator
1313

1414
logger = logging.getLogger("e3.aws.s3")
@@ -127,24 +127,45 @@ def push(
127127
else:
128128
raise KeyExistsError(key)
129129

130+
def get_object(self, key: str) -> dict[str, Any]:
131+
"""Get an object from S3.
132+
133+
:param key: object key
134+
:raises KeyNotFoundError: the key doesn't exist
135+
"""
136+
try:
137+
return self.client.get_object(Bucket=self.bucket, Key=key)
138+
except ClientError as e:
139+
# Handle the error when key doesn't exist
140+
if e.response["Error"]["Code"] == "NoSuchKey":
141+
raise KeyNotFoundError(key) from e
142+
143+
raise e
144+
145+
def get_body(self, key: str) -> IO[bytes]:
146+
"""Get the body of an object from S3.
147+
148+
:param key: object key
149+
:raises KeyNotFoundError: the key doesn't exist
150+
"""
151+
return self.get_object(key)["Body"]
152+
130153
def get(self, key: str, default: bytes | None = None) -> bytes:
131154
"""Get content from S3.
132155
133156
If default is None, an exception will be raised if the key
134157
doesn't exist in the S3 bucket.
135158
136159
:param key: object key
160+
:param default: default content to return if the key doesn't exist
137161
:raises KeyNotFoundError: the key doesn't exist
138162
"""
139163
try:
140-
return self.client.get_object(Bucket=self.bucket, Key=key)["Body"].read()
141-
except ClientError as e:
142-
# Handle the error when key doesn't exist
143-
if e.response["Error"]["Code"] == "NoSuchKey":
144-
if default is not None:
145-
return default
164+
return self.get_body(key).read()
165+
except KeyNotFoundError as e:
166+
if default is not None:
167+
return default
146168

147-
raise KeyNotFoundError(key) from e
148169
raise e
149170

150171
def iterate(self, *, prefix: str | None = None) -> Iterable[dict[str, Any]]:

0 commit comments

Comments
 (0)