Cloud Storage 사용

Cloud Storage를 사용하여 영화, 이미지 또는 기타 정적 콘텐츠와 같은 파일을 저장하고 제공할 수 있습니다.

이 문서는 앱에서 Google Cloud 클라이언트 라이브러리를 사용하여 Cloud Storage에 데이터를 저장하고 검색하는 방법을 설명합니다.

시작하기 전에

  • App Engine의 Python용 'Hello, World!'의 안내에 따라 환경과 프로젝트를 설정하고, App Engine에서 Python 앱이 구조화되는 방식을 이해합니다. 이 문서에 설명된 샘플 애플리케이션을 실행할 때 필요하므로 프로젝트 ID를 기록해 둡니다.

  • 다음 명령어를 호출하여 애플리케이션용 Cloud Storage 버킷을 만듭니다.

    gsutil mb gs://[YOUR_BUCKET_NAME]
    
  • 공개 읽기 가능 버킷으로 만들어 파일을 제공할 수 있도록 합니다.

    gsutil defacl set public-read gs://[YOUR_BUCKET_NAME]
    

샘플 다운로드

저장소를 복제하려면 다음을 사용하세요.

git clone https://github.com/GoogleCloudPlatform/python-docs-samples
cd python-docs-samples/appengine/flexible/storage

프로젝트 구성 수정 및 종속 항목 설치

app.yaml에서 GOOGLE_STORAGE_BUCKET을 설정합니다. 이 값은 이전에 만든 Cloud Storage 버킷의 이름입니다.

env_variables:
    CLOUD_STORAGE_BUCKET: your-bucket-name

requirements.txt에서 google-cloud-storage 라이브러리를 포함해야 합니다. Cloud Storage 기능을 제공하기 때문입니다.

Flask==2.1.0; python_version > '3.6'
Flask==2.0.3; python_version < '3.7'
werkzeug==2.1.2; python_version > '3.6'
werkzeug==2.0.3; python_version < '3.7'
google-cloud-storage==2.0.0; python_version < '3.7'
google-cloud-storage==2.1.0; python_version > '3.6'
gunicorn==20.1.0; python_version > '3.0'
gunicorn==19.10.0; python_version < '3.0'

애플리케이션 코드

샘플 애플리케이션은 사용자에게 Cloud Storage에 저장할 파일을 제공하라는 메시지를 표시하는 웹페이지를 제공합니다. 사용자가 파일을 선택하고 제출을 클릭하면 업로드 핸들러가 파일 콘텐츠를 Cloud Storage blob에 로드하고 Cloud Storage 버킷에 씁니다.

파일이 Cloud Storage에 업로드된 후에는 이 파일의 공개 URL이 반환되며, Cloud Storage에서 직접 파일을 제공하는 데 이 URL을 사용할 수 있습니다. 나중에 사용할 수 있도록 이 값을 앱에 저장해야 합니다.

import logging
import os
from typing import Union

from flask import Flask, request
from google.cloud import storage

app = Flask(__name__)

# Configure this environment variable via app.yaml
CLOUD_STORAGE_BUCKET = os.environ['CLOUD_STORAGE_BUCKET']

@app.route('/')
def index() -> str:
    return """
<form method="POST" action="/upload" enctype="multipart/form-data">
    <input type="file" name="file">
    <input type="submit">
</form>
"""

@app.route('/upload', methods=['POST'])
def upload() -> str:
    """Process the uploaded file and upload it to Google Cloud Storage."""
    uploaded_file = request.files.get('file')

    if not uploaded_file:
        return 'No file uploaded.', 400

    # Create a Cloud Storage client.
    gcs = storage.Client()

    # Get the bucket that the file will be uploaded to.
    bucket = gcs.get_bucket(CLOUD_STORAGE_BUCKET)

    # Create a new blob and upload the file's content.
    blob = bucket.blob(uploaded_file.filename)

    blob.upload_from_string(
        uploaded_file.read(),
        content_type=uploaded_file.content_type
    )

    # Make the blob public. This is not necessary if the
    # entire bucket is public.
    # See https://cloud.google.com/storage/docs/access-control/making-data-public.
    blob.make_public()

    # The public URL can be used to directly access the uploaded file via HTTP.
    return blob.public_url

@app.errorhandler(500)
def server_error(e: Union[Exception, int]) -> str:
    logging.exception('An error occurred during a request.')
    return """
    An internal error occurred: <pre>{}</pre>
    See logs for full stacktrace.
    """.format(e), 500

if __name__ == '__main__':
    # This is used when running locally. Gunicorn is used to run the
    # application on Google App Engine. See entrypoint in app.yaml.
    app.run(host='127.0.0.1', port=8080, debug=True)

추가 정보

Cloud Storage에 대한 자세한 내용은 Cloud Storage 문서를 참조하세요.