forked from mtusi2026/mtusi2026lab4
лаба 4
This commit is contained in:
@@ -0,0 +1,71 @@
|
||||
|
||||
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
|
||||
Reference in New Issue
Block a user