Files
mtusi2026lab4/app/s3.py
T

53 lines
1.5 KiB
Python

from datetime import timedelta
from io import BytesIO
from minio import Minio
from app.config import config
class S3Storage:
def __init__(self) -> None:
common = dict(
access_key=config.S3_ACCESS_KEY,
secret_key=config.S3_SECRET_KEY,
secure=config.S3_SECURE,
region="us-east-1",
)
self._client = Minio(config.S3_ENDPOINT, **common)
self._presign_client = Minio(config.S3_PUBLIC_ENDPOINT, **common)
self._bucket = config.S3_BUCKET
@property
def client(self) -> Minio:
return self._client
@property
def bucket(self) -> str:
return self._bucket
def ensure_bucket(self) -> None:
if not self._client.bucket_exists(self._bucket):
self._client.make_bucket(self._bucket)
def put(self, key: str, data: bytes, content_type: str) -> None:
self._client.put_object(
self._bucket, key, BytesIO(data), len(data), content_type=content_type
)
def get(self, key: str):
return self._client.get_object(self._bucket, key)
def stat(self, key: str):
return self._client.stat_object(self._bucket, key)
def remove(self, key: str) -> None:
self._client.remove_object(self._bucket, key)
def presigned_put(self, key: str, expires_seconds: int = 300) -> str:
return self._presign_client.presigned_put_object(
self._bucket, key, expires=timedelta(seconds=expires_seconds)
)
s3 = S3Storage()