forked from mtusi2026/mtusi2026lab4
72 lines
1.7 KiB
Python
72 lines
1.7 KiB
Python
|
|
import asyncio
|
|
import os
|
|
from pathlib import Path
|
|
|
|
import boto3
|
|
from botocore.config import Config
|
|
|
|
|
|
def read_secret(env_name: str) -> str:
|
|
path = os.environ[env_name]
|
|
return Path(path).read_text(encoding="utf-8").strip()
|
|
|
|
|
|
s3_client = boto3.client(
|
|
"s3",
|
|
endpoint_url=os.environ["S3_ENDPOINT"],
|
|
region_name=os.getenv("S3_REGION", "us-east-1"),
|
|
aws_access_key_id=read_secret("S3_ACCESS_KEY_ID_FILE"),
|
|
aws_secret_access_key=read_secret("S3_SECRET_ACCESS_KEY_FILE"),
|
|
config=Config(
|
|
signature_version="s3v4",
|
|
connect_timeout=2,
|
|
read_timeout=3,
|
|
retries={"total_max_attempts": 1, "mode": "standard"},
|
|
s3={"addressing_style": "path"},
|
|
),
|
|
)
|
|
|
|
S3_BUCKET = os.environ["S3_BUCKET"]
|
|
|
|
|
|
async def put_object(key: str, body: bytes, content_type: str) -> None:
|
|
await asyncio.to_thread(
|
|
s3_client.put_object,
|
|
Bucket=S3_BUCKET,
|
|
Key=key,
|
|
Body=body,
|
|
ContentType=content_type,
|
|
)
|
|
|
|
|
|
async def get_object(key: str) -> bytes:
|
|
def download() -> bytes:
|
|
response = s3_client.get_object(Bucket=S3_BUCKET, Key=key)
|
|
stream = response["Body"]
|
|
try:
|
|
return stream.read()
|
|
finally:
|
|
stream.close()
|
|
|
|
return await asyncio.to_thread(download)
|
|
|
|
|
|
async def delete_object(key: str) -> None:
|
|
await asyncio.to_thread(
|
|
s3_client.delete_object,
|
|
Bucket=S3_BUCKET,
|
|
Key=key,
|
|
)
|
|
|
|
|
|
async def ping_storage() -> bool:
|
|
try:
|
|
await asyncio.to_thread(
|
|
s3_client.head_bucket,
|
|
Bucket=S3_BUCKET,
|
|
)
|
|
return True
|
|
except Exception:
|
|
return False
|