|
| 1 | +# -*- coding: utf-8 -*- |
| 2 | + |
| 3 | +""" |
| 4 | +S3 bucket |
| 5 | +""" |
| 6 | + |
| 7 | +import boto3 |
| 8 | +import logging |
| 9 | +from typing import Any, Optional |
| 10 | + |
| 11 | +from ..logger import LoggerSetup |
| 12 | + |
| 13 | + |
| 14 | +class Bucket(object): |
| 15 | + """ |
| 16 | + S3 bucket class |
| 17 | +
|
| 18 | + :author: Garden Linux Maintainers |
| 19 | + :copyright: Copyright 2024 SAP SE |
| 20 | + :package: gardenlinux |
| 21 | + :subpackage: s3 |
| 22 | + :since: 0.8.0 |
| 23 | + :license: https://www.apache.org/licenses/LICENSE-2.0 |
| 24 | + Apache License, Version 2.0 |
| 25 | + """ |
| 26 | + |
| 27 | + def __init__( |
| 28 | + self, |
| 29 | + bucket_name: str, |
| 30 | + endpoint_url: Optional[str] = None, |
| 31 | + s3_resource_config: Optional[dict[str, Any]] = None, |
| 32 | + logger: Optional[logging.Logger] = None, |
| 33 | + ): |
| 34 | + """ |
| 35 | + Constructor __init__(Bucket) |
| 36 | +
|
| 37 | + :param bucket_name: S3 bucket name |
| 38 | + :param endpoint_url: S3 endpoint URL |
| 39 | + :param s3_resource_config: Additional boto3 S3 config values |
| 40 | + :param logger: Logger instance |
| 41 | +
|
| 42 | + :since: 0.8.0 |
| 43 | + """ |
| 44 | + |
| 45 | + if logger is None or not logger.hasHandlers(): |
| 46 | + logger = LoggerSetup.get_logger("gardenlinux.s3") |
| 47 | + |
| 48 | + if s3_resource_config is None: |
| 49 | + s3_resource_config = {} |
| 50 | + |
| 51 | + if endpoint_url is not None: |
| 52 | + s3_resource_config["endpoint_url"] = endpoint_url |
| 53 | + |
| 54 | + self._s3_resource = boto3.resource("s3", **s3_resource_config) |
| 55 | + |
| 56 | + self._bucket = self._s3_resource.Bucket(bucket_name) |
| 57 | + self._logger = logger |
| 58 | + |
| 59 | + @property |
| 60 | + def objects(self): |
| 61 | + """ |
| 62 | + Returns a list of all objects in a bucket. |
| 63 | +
|
| 64 | + :return: (list) S3 bucket objects |
| 65 | + :since: 0.8.0 |
| 66 | + """ |
| 67 | + |
| 68 | + return self._bucket.objects.all() |
| 69 | + |
| 70 | + def __getattr__(self, name): |
| 71 | + """ |
| 72 | + python.org: Called when an attribute lookup has not found the attribute in |
| 73 | + the usual places (i.e. it is not an instance attribute nor is it found in the |
| 74 | + class tree for self). |
| 75 | +
|
| 76 | + :param name: Attribute name |
| 77 | +
|
| 78 | + :return: (mixed) Attribute |
| 79 | + :since: 0.8.0 |
| 80 | + """ |
| 81 | + |
| 82 | + return getattr(self._bucket, name) |
0 commit comments