2 File in charge of providing a boiled down interface for interracting with an s3 bucket.
5from typing
import List, Union, Dict, Any, Optional
7from botocore.client
import Config
8from botocore.exceptions
import BotoCoreError, ClientError
9from display_tty
import Disp, TOML_CONF, FILE_DESCRIPTOR, SAVE_TO_FILE, FILE_NAME
10from ..components
import CONST
15 Class to manage interaction with an S3-compatible bucket like MinIO.
18 def __init__(self, error: int = 84, success: int = 0, debug: bool =
False) ->
None:
30 logger=self.__class__.__name__
37 Connect to the S3 bucket or MinIO service.
40 int: success or error code.
46 endpoint_url=f
"{CONST.MINIO_HOST}:{CONST.MINIO_PORT}",
47 aws_access_key_id=CONST.MINIO_ROOT_USER,
48 aws_secret_access_key=CONST.MINIO_ROOT_PASSWORD,
49 config=Config(signature_version=
's3v4')
53 self.
disp.log_info(
"Connection to MinIO S3 successful.",
"connect")
55 except (BotoCoreError, ClientError)
as e:
57 f
"Failed to connect to MinIO: {str(e)}",
64 Check if the connection to the S3-compatible service is active.
67 bool: True if connected, False otherwise.
70 self.
disp.log_error(
"No connection object found.",
"is_connected")
76 self.
disp.log_info(
"Connection is active.",
"is_connected")
78 except (BotoCoreError, ClientError, ConnectionError)
as e:
80 f
"Connection check failed: {str(e)}",
87 Disconnect from the S3-compatible service by setting the connection to None.
90 int: success or error code.
93 self.
disp.log_warning(
94 "No active connection to disconnect.",
102 "Disconnected from the S3-compatible service.",
106 except Exception
as e:
108 f
"Failed to disconnect: {str(e)}",
115 Retrieve a list of all bucket names.
118 Union[List[str], int]: A list of bucket names or error code.
122 raise ConnectionError(
"No connection established.")
123 buckets = [bucket.name
for bucket
in self.
connection.buckets.all()]
125 except (BotoCoreError, ClientError, ConnectionError)
as e:
127 f
"Error fetching bucket names: {str(e)}",
137 bucket_name (str): Name of the bucket to create.
140 int: success or error code.
144 raise ConnectionError(
"No connection established.")
147 f
"Bucket '{bucket_name}' created successfully.",
151 except (BotoCoreError, ClientError, ConnectionError)
as e:
153 f
"Failed to create bucket '{bucket_name}': {str(e)}",
158 def upload_file(self, bucket_name: str, file_path: str, key_name: Optional[str] =
None) -> int:
160 Upload a file to the specified bucket.
163 bucket_name (str): Name of the target bucket.
164 file_path (str): Path of the file to upload.
165 key_name (Optional[str]): Name to save the file as in the bucket. Defaults to the file path name.
168 int: success or error code.
170 key_name = key_name
or file_path
173 raise ConnectionError(
"No connection established.")
176 msg = f
"File '{file_path}' uploaded to bucket "
177 msg += f
"'{bucket_name}' as '{key_name}'."
178 self.
disp.log_info(msg,
"upload_file")
180 except (BotoCoreError, ClientError, ConnectionError)
as e:
181 msg = f
"Failed to upload file '{file_path}' to bucket "
182 msg += f
"'{bucket_name}': {str(e)}"
183 self.
disp.log_error(msg,
"upload_file")
186 def download_file(self, bucket_name: str, key_name: str, destination_path: str) -> int:
188 Download a file from the specified bucket.
191 bucket_name (str): Name of the target bucket.
192 key_name (str): Name of the file to download.
193 destination_path (str): Local path where the file will be saved.
196 int: success or error code.
200 raise ConnectionError(
"No connection established.")
202 key_name, destination_path)
203 msg = f
"File '{key_name}' downloaded from bucket "
204 msg += f
"'{bucket_name}' to '{destination_path}'."
205 self.
disp.log_info(msg,
"download_file")
207 except (BotoCoreError, ClientError, ConnectionError)
as e:
208 msg = f
"Failed to download file '{key_name}'"
209 msg += f
" from bucket '{bucket_name}': {str(e)}"
210 self.
disp.log_error(msg,
"download_file")
215 Delete a file from the specified bucket.
218 bucket_name (str): Name of the bucket.
219 key_name (str): Name of the file to delete.
222 int: success or error code.
226 raise ConnectionError(
"No connection established.")
229 f
"File '{key_name}' deleted from bucket '{bucket_name}'.",
233 except (BotoCoreError, ClientError, ConnectionError)
as e:
234 msg = f
"Failed to delete file '{key_name}' from bucket "
235 msg += f
"'{bucket_name}': {str(e)}"
236 self.
disp.log_error(msg,
"delete_file")
244 bucket_name (str): Name of the bucket to delete.
247 int: success or error code.
251 raise ConnectionError(
"No connection established.")
254 f
"Bucket '{bucket_name}' deleted successfully.",
258 except (BotoCoreError, ClientError, ConnectionError)
as e:
260 f
"Failed to delete bucket '{bucket_name}': {str(e)}",
267 List all files in the specified bucket.
270 bucket_name (str): Name of the bucket.
273 Union[List[str], int]: List of file names or error code.
277 raise ConnectionError(
"No connection established.")
280 files.append(obj.key)
282 except (BotoCoreError, ClientError, ConnectionError)
as e:
283 msg = f
"Failed to retrieve files from bucket '{bucket_name}'"
285 self.
disp.log_error(msg,
"get_bucket_files")
288 def get_bucket_file(self, bucket_name: str, key_name: str) -> Union[Dict[str, Any], int]:
290 Get information about a specific file in the bucket.
293 bucket_name (str): Name of the bucket.
294 key_name (str): Name of the file.
297 Union[Dict[str, Any], int]: File metadata (path and size) or error code.
301 raise ConnectionError(
"No connection established.")
303 return {
'file_path': key_name,
'file_size': obj.content_length}
304 except (BotoCoreError, ClientError, ConnectionError)
as e:
305 msg = f
"Failed to get file '{key_name}'"
306 msg += f
"from bucket '{bucket_name}': {str(e)}"
307 self.
disp.log_error(msg,
"get_bucket_file")
Optional[boto3.resource] connection
Union[List[str], int] get_bucket_names(self)
int delete_file(self, str bucket_name, str key_name)
int upload_file(self, str bucket_name, str file_path, Optional[str] key_name=None)
None __init__(self, int error=84, int success=0, bool debug=False)
Union[List[str], int] get_bucket_files(self, str bucket_name)
Union[Dict[str, Any], int] get_bucket_file(self, str bucket_name, str key_name)
int create_bucket(self, str bucket_name)
int delete_bucket(self, str bucket_name)
int download_file(self, str bucket_name, str key_name, str destination_path)