|
| 1 | +import uuid |
| 2 | + |
| 3 | +import boto3 # type: ignore[import-untyped] |
| 4 | +from botocore.exceptions import ClientError # type: ignore[import-untyped] |
| 5 | + |
| 6 | +from app.core.config import settings |
| 7 | +from app.core.exceptions import S3_001, AppException |
| 8 | +from app.s3.schemas import S3PresignedUploadResp |
| 9 | +from app.s3.service import S3Service |
| 10 | +from app.schemas.common import S3FileType |
| 11 | + |
| 12 | + |
| 13 | +class S3ServiceImpl(S3Service): |
| 14 | + def generate_presigned_upload_url( |
| 15 | + self, file_name: str, file_type: S3FileType, content_type: str |
| 16 | + ) -> S3PresignedUploadResp: |
| 17 | + bucket = ( |
| 18 | + settings.s3_public_bucket |
| 19 | + if file_type == S3FileType.STORE |
| 20 | + else settings.s3_private_bucket |
| 21 | + ) |
| 22 | + s3_key = f"{file_type.value.lower()}/{uuid.uuid4()}/{file_name}" |
| 23 | + |
| 24 | + client = boto3.client( |
| 25 | + "s3", |
| 26 | + aws_access_key_id=settings.aws_access_key_id, |
| 27 | + aws_secret_access_key=settings.aws_secret_access_key, |
| 28 | + region_name=settings.aws_region, |
| 29 | + endpoint_url=f"https://s3.{settings.aws_region}.amazonaws.com", |
| 30 | + ) |
| 31 | + try: |
| 32 | + url: str = client.generate_presigned_url( |
| 33 | + "put_object", |
| 34 | + Params={"Bucket": bucket, "Key": s3_key, "ContentType": content_type}, |
| 35 | + ExpiresIn=settings.s3_presigned_expiry, |
| 36 | + ) |
| 37 | + except ClientError as e: |
| 38 | + raise AppException(S3_001) from e |
| 39 | + |
| 40 | + return S3PresignedUploadResp(url=url, s3Key=s3_key) |
0 commit comments