58 lines
1.5 KiB
Python
58 lines
1.5 KiB
Python
from __future__ import annotations
|
|
|
|
from dataclasses import dataclass
|
|
from pathlib import Path
|
|
|
|
from minio import Minio
|
|
from minio.error import S3Error
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class StorageConfig:
|
|
endpoint: str
|
|
access_key: str
|
|
secret_key: str
|
|
bucket: str
|
|
secure: bool = False
|
|
|
|
|
|
class ObjectStorage:
|
|
def __init__(self, config: StorageConfig) -> None:
|
|
self.config = config
|
|
self.client = Minio(
|
|
endpoint=config.endpoint,
|
|
access_key=config.access_key,
|
|
secret_key=config.secret_key,
|
|
secure=config.secure,
|
|
)
|
|
|
|
def ensure_bucket(self) -> None:
|
|
if not self.client.bucket_exists(self.config.bucket):
|
|
self.client.make_bucket(self.config.bucket)
|
|
|
|
def object_exists(self, storage_key: str) -> bool:
|
|
try:
|
|
self.client.stat_object(self.config.bucket, storage_key)
|
|
return True
|
|
except S3Error as exc:
|
|
if exc.code in {"NoSuchKey", "NoSuchObject", "NoSuchBucket"}:
|
|
return False
|
|
raise
|
|
|
|
def upload(
|
|
self,
|
|
*,
|
|
source_path: Path,
|
|
storage_key: str,
|
|
mime_type: str,
|
|
) -> None:
|
|
self.client.fput_object(
|
|
bucket_name=self.config.bucket,
|
|
object_name=storage_key,
|
|
file_path=str(source_path),
|
|
content_type=mime_type,
|
|
)
|
|
|
|
def remove(self, storage_key: str) -> None:
|
|
self.client.remove_object(self.config.bucket, storage_key)
|