forked from mtusi2026/mtusi2026lab4
39 lines
1.1 KiB
Python
39 lines
1.1 KiB
Python
import boto3
|
|
from botocore.config import Config
|
|
from app.core.config import settings
|
|
|
|
|
|
def client(endpoint_url=None):
|
|
return boto3.client(
|
|
"s3", endpoint_url=endpoint_url or settings.s3_endpoint_url,
|
|
aws_access_key_id=settings.s3_access_key,
|
|
aws_secret_access_key=settings.s3_secret_key,
|
|
region_name=settings.s3_region,
|
|
config=Config(signature_version="s3v4", connect_timeout=3, read_timeout=15, retries={"max_attempts": 2}, s3={"addressing_style": "path"}),
|
|
)
|
|
|
|
|
|
def ensure_bucket() -> None:
|
|
s3 = client()
|
|
try:
|
|
s3.head_bucket(Bucket=settings.s3_bucket)
|
|
except Exception:
|
|
s3.create_bucket(Bucket=settings.s3_bucket)
|
|
|
|
|
|
def presigned_client():
|
|
return client(endpoint_url=settings.s3_public_endpoint_url)
|
|
|
|
|
|
def create_presigned_upload_url(object_key: str, content_type: str) -> str:
|
|
s3 = presigned_client()
|
|
|
|
return s3.generate_presigned_url(
|
|
ClientMethod="put_object",
|
|
Params={
|
|
"Bucket": settings.s3_bucket,
|
|
"Key": object_key,
|
|
"ContentType": content_type,
|
|
},
|
|
ExpiresIn=settings.presigned_upload_ttl_seconds,
|
|
) |