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 |
---|