|
8 | 8 | import boto3 |
9 | 9 |
|
10 | 10 | if TYPE_CHECKING: |
11 | | - from typing import Any, BinaryIO |
| 11 | + from typing import Any, BinaryIO, IO |
12 | 12 | from collections.abc import Iterable, Iterator |
13 | 13 |
|
14 | 14 | logger = logging.getLogger("e3.aws.s3") |
@@ -127,24 +127,45 @@ def push( |
127 | 127 | else: |
128 | 128 | raise KeyExistsError(key) |
129 | 129 |
|
| 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 | + |
130 | 153 | def get(self, key: str, default: bytes | None = None) -> bytes: |
131 | 154 | """Get content from S3. |
132 | 155 |
|
133 | 156 | If default is None, an exception will be raised if the key |
134 | 157 | doesn't exist in the S3 bucket. |
135 | 158 |
|
136 | 159 | :param key: object key |
| 160 | + :param default: default content to return if the key doesn't exist |
137 | 161 | :raises KeyNotFoundError: the key doesn't exist |
138 | 162 | """ |
139 | 163 | 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 |
146 | 168 |
|
147 | | - raise KeyNotFoundError(key) from e |
148 | 169 | raise e |
149 | 170 |
|
150 | 171 | def iterate(self, *, prefix: str | None = None) -> Iterable[dict[str, Any]]: |
|
0 commit comments