[230908] 졸업프로젝트

⭐️·2023년 9월 8일
0

졸업프로젝트

목록 보기
2/4

Dall-e api에서 반환된 이미지의 링크를 S3에 저장하도록 구현하였다.

먼저, uuid를 생성하여 유일한 객체 이름을 만들었다.

object_name = str(uuid.uuid1()) + '.jpg'

S3 client 객체를 만들었다.

s3_client = boto3.client(
    's3',
    aws_access_key_id=ACCESS_KEY,
    aws_secret_access_key=SECRET_KEY
    )

만약 저장된 파일을 S3에 업로드하는 경우이다.

def upload_file_to_s3(file_path, object_name): 
    try:
        s3_client.upload_file(file_path, BUCKET_NAME, object_name)
    except ClientError as e:
        return None
  
    image_url = f'{S3_URL}/{object_name}'
    return image_url

upload_file_to_s3(file_path, filename)

다음은, 읽기 가능한 파일 같은 객체를 S3 업로드하는 경우이다.

# file: 텍스트가 아닌 바이너리모드로 열린 파일 객체
file = requests.get(dalle_url).content

try:
    s3_client.upload_fileobj(
        io.BytesIO(file),
        BUCKET_NAME,
       object_name
    )
except ClientError as e:
    return None

image_url = f"{S3_URL}/{object_name}"
return image_url

결과
1

0개의 댓글