File size: 1,485 Bytes
30099ac
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
from PIL.ImageFile import ImageFile
import boto3

import tempfile
import os
import logging
from dotenv import load_dotenv

load_dotenv(verbose=True)

AWS_ACCESS_KEY = os.getenv("AWS_ACCESS_KEY_ID")
AWS_SECRET_ACCESS_KEY = os.getenv("AWS_SECRET_ACCESS_KEY")
AWS_BUCKET_NAME = os.getenv("AWS_S3_BUCKET_NAME")
AWS_REGION = os.getenv("AWS_REGION")


class Bucket:
    def __init__(self):
        self.bucket_name = AWS_BUCKET_NAME
        self.s3 = boto3.client(
            "s3",
            region_name=AWS_REGION,
            aws_access_key_id=AWS_ACCESS_KEY,
            aws_secret_access_key=AWS_SECRET_ACCESS_KEY,
        )

    def upload_file(self, image: ImageFile, uuid: str):
        key = f"{uuid}.png"
        try:
            logging.info(
                f"Uploading image to S3 with key: s3://{self.bucket_name}/{key}"
            )
            with tempfile.TemporaryFile() as fp:
                image.save(fp, "PNG")
                fp.seek(0)
                self.s3.upload_fileobj(fp, self.bucket_name, key)
        except Exception as e:
            logging.error(e)
            raise e

    def get_presigned_url(self, uuid: str):
        key = f"{uuid}.png"
        try:
            url = self.s3.generate_presigned_url(
                "get_object",
                Params={"Bucket": self.bucket_name, "Key": key},
                ExpiresIn=3600,
            )
            return url
        except Exception as e:
            logging.error(e)
            raise e