songining

flask ์›น์„œ๋ฒ„์— aws s3๋ฒ„ํ‚ท์„ ์—ฐ๊ฒฐ์‹œํ‚ค๊ธฐ ์œ„ํ•ด ํŒŒ์ด์ฌ ํŒŒ์ผ์„ ๋”ฐ๋กœ ์ž‘์„ฑํ–ˆ๋‹ค. 

 

pip install boto3

config.py ์ž‘์„ฑ (AWS ๋‚ด ๋ณด์•ˆ ์ž๊ฒฉ์ฆ๋ช…์—์„œ ํ‚ค ์–ป์–ด์˜ค๊ธฐ) 

AWS_ACCESS_KEY = "์ž‘์„ฑ"
AWS_SECRET_KEY = "์ž‘์„ฑ"
BUCKET_NAME = "๋ฒ„ํ‚ท์ด๋ฆ„"

AWS S3 bucket ํŒŒ์ผ ์—…๋กœ๋“œ ๋ฐ url ๊ฐ€์ ธ์˜ค๊ธฐ 

- upload_file ํ•จ์ˆ˜์˜ ๋งค๊ฐœ๋ณ€์ˆ˜ file_path๋Š” ๋‚ด ๋กœ์ปฌ ํ™˜๊ฒฝ ๋‚ด์— ๋งŒ๋“ค์–ด์ง„ ์ด๋ฏธ์ง€๊ฐ€ ์ €์žฅ๋œ ์ƒ๋Œ€๊ฒฝ๋กœ ์ด๋‹ค. ํ•ด๋‹น ๊ฒฝ๋กœ์˜ ์ด๋ฏธ์ง€๋ฅผ s3 bucket์— ์˜ฌ๋ ค image url์„ ์–ป์–ด์˜ค๊ธฐ ์œ„ํ•ด ํ•จ์ˆ˜๋ฅผ ๋”ฐ๋กœ ๊ตฌํ˜„ํ•˜์˜€๋‹ค. 

import boto3
from config import *
from botocore.exceptions import ClientError
import logging

#S3 ํŒŒ์ผ ์—…๋กœ๋“œ ๋ฐ url ๊ฐ€์ ธ์˜ค๊ธฐ 
def upload_file(file_path):

    """Upload a file to an S3 bucket

    :param file_name: File to upload
    :param bucket: Bucket to upload to
    :param object_name: S3 object name. If not specified then file_name is used
    :return: True if file was uploaded, else False
    """
    # ํŒŒ์ผ ๊ฐ€์ ธ์˜ฌ ๊ฒฝ๋กœ 
    file_path='ํŒŒ์ผ ๊ฒฝ๋กœ'
    # ์ƒ์„ฑํ•œ bucket ์ด๋ฆ„ 
    bucket = BUCKET_NAME

    # s3 ํŒŒ์ผ ๊ฐ์ฒด ์ด๋ฆ„
    object_name = 's3์— ์ €์žฅํ•  ๊ฐ์ฒด ์ด๋ฆ„'

    # aws region 
    location = 'ap-northeast-2'
   
    #์ž๊ฒฉ ์ฆ๋ช… 
    s3_client = boto3.client(
    's3',
    aws_access_key_id=AWS_ACCESS_KEY,
    aws_secret_access_key=AWS_SECRET_KEY
    )

     # Upload the file
    try:
        s3_client.upload_file(file_path, bucket, object_name)
    except ClientError as e:
        logging.error(e)
        return None
    image_url = f'https://{BUCKET_NAME}.s3.{location}.amazonaws.com/{object_name}'
    return image_url

์ฐธ๊ณ : https://boto3.amazonaws.com/v1/documentation/api/latest/guide/s3-uploading-files.html

'BACKEND > Flask' ์นดํ…Œ๊ณ ๋ฆฌ์˜ ๋‹ค๋ฅธ ๊ธ€

react - flask CORS ์—๋Ÿฌ ํ•ด๊ฒฐ  (0) 2021.11.11