본문 바로가기
Python

DRF에서 Google Cloud Storage 사용하기 - Django에서 GCS 연결하기

by Zih0 2021. 8. 8.

ref :  https://django-storages.readthedocs.io/en/latest/backends/gcloud.html#installation

 

Google Cloud Storage — django-storages 1.11.1 documentation

Your Google Storage bucket name, as a string. Required. Your Google Cloud project ID. If unset, falls back to the default inferred from the environment. The OAuth 2 credentials to use for the connection. If unset, falls back to the default inferred from th

django-storages.readthedocs.io

 

패키지 설치

Django 프로젝트가 있는 폴더에서 아래 패키지를 설치합니다.

$ pip install django-storages[google] google-auth

 

settings.py 수정

그 다음 settings.py 파일에 아래 코드를 추가합니다.

from google.oauth2 import service_account


DEFAULT_FILE_STORAGE = 'storages.backends.gcloud.GoogleCloudStorage'


GS_BUCKET_NAME = 'BUCKET_NAME' 
GS_PROJECT_ID = 'PROJECT_ID' #json 파일에서 확인 가능

# 다운로드 받았던 json파일의 경로를 설정해줍니다.
GS_CREDENTIALS = service_account.Credentials.from_service_account_file(
    "path/credentials.json"
)

 

 

이미지 저장

이제 API를 통해 이미지 파일을 받았을 때, 이미지를 GCS에 저장해보도록 하겠습니다.

 

우선 이미지를 GSC에 저장받는 함수를 utils폴더에 따로 생성했습니다.

#utils/upload.py

from storages.backends.gcloud import GoogleCloudStorage
from datetime import datetime

storage = GoogleCloudStorage()

# 이미지 업로드 함수
def upload_image(file, directory):
    try:
        target_path = f"/{directory}/{datetime.timestamp(datetime.now())}.jpg"
        path = storage.save(target_path, file)
        return storage.url(path)
    except Exception as e:
        print(e)

해당 함수는 파일과, 버킷에 들어갈 폴더명을 파라미터로 받습니다.

파일을 저장 한 후에 버킷에 저장된 이미지 url을 반환합니다.

 

이 함수를 사용한 예시 view입니다.

from server.utils.upload import upload_image


@api_view(["POST"])
def upload_test(request):
    image = request.FILES["image"]
    # image파일, 폴더명
    public_url = upload_image(image, "dir")
    return Response({"url": public_url})

 

댓글