Files
mtusi2026lab5/app/s3_client.py
T

40 lines
1.2 KiB
Python

import os
import asyncio
from minio import Minio
S3_ENDPOINT = os.getenv("S3_ENDPOINT", "http://s3:8333").replace("http://", "").replace("https://", "")
S3_ACCESS_KEY = os.getenv("S3_ACCESS_KEY", "admin")
S3_SECRET_KEY = os.getenv("S3_SECRET_KEY", "admin")
S3_BUCKET_NAME = os.getenv("S3_BUCKET_NAME", "messenger-attachments")
S3_SECURE = os.getenv("S3_ENDPOINT", "http://s3:8333").startswith("https://")
s3_client = Minio(
S3_ENDPOINT,
access_key=S3_ACCESS_KEY,
secret_key=S3_SECRET_KEY,
secure=S3_SECURE
)
def get_s3_client():
return s3_client
async def upload_file_to_s3(object_name: str, file_path: str, content_type: str):
loop = asyncio.get_running_loop()
await loop.run_in_executor(
None,
lambda: s3_client.fput_object(S3_BUCKET_NAME, object_name, file_path, content_type=content_type)
)
async def get_file_from_s3(object_name: str):
loop = asyncio.get_running_loop()
return await loop.run_in_executor(
None,
lambda: s3_client.get_object(S3_BUCKET_NAME, object_name)
)
async def delete_file_from_s3(object_name: str):
loop = asyncio.get_running_loop()
await loop.run_in_executor(
None,
lambda: s3_client.remove_object(S3_BUCKET_NAME, object_name)
)