Cloud Storage 읽기 및 쓰기

이 문서에서는 Cloud Storage 클라이언트 라이브러리를 사용하여 데이터를 저장 및 검색하는 방법을 설명합니다. 여기서는 Cloud Storage 설정에 설명된 작업을 완료하여 Cloud Storage 버킷을 활성화하고 클라이언트 라이브러리를 다운로드했다고 가정합니다. 또한 App Engine 애플리케이션을 빌드하는 방법을 알고 있다고 가정합니다.

추가 코드 샘플은 Cloud Storage 클라이언트 라이브러리를 참조하세요.

필수 가져오기

클라이언트 라이브러리를 사용하여 Cloud Storage에 액세스하려면 아래의 코드 스니펫을 사용합니다.

# Imports the Google Cloud client library
from google.cloud import storage

# Instantiates a client
storage_client = storage.Client()

# The name for the new bucket
bucket_name = "my-new-bucket"

# Creates the new bucket
bucket = storage_client.create_bucket(bucket_name)

print(f"Bucket {bucket.name} created.")

Cloud Storage 버킷 지정

Cloud Storage에서 작업을 수행하기 전에 버킷 이름을 제공해야 합니다.

# Imports the Google Cloud client library
from google.cloud import storage

# Instantiates a client
storage_client = storage.Client()

# The name for the new bucket
bucket_name = "my-new-bucket"

# Creates the new bucket
bucket = storage_client.create_bucket(bucket_name)

print(f"Bucket {bucket.name} created.")

버킷 이름을 지정하는 가장 쉬운 방법은 프로젝트에 기본 버킷을 사용하는 것입니다. 프로젝트의 기본 버킷을 생성한 경우에만 get_default_gcs_bucket_name 호출이 성공합니다.

Cloud Storage에 쓰기

다음 샘플은 버킷에 쓰는 방법을 보여줍니다.

from google.cloud import storage

def write_read(bucket_name, blob_name):
    """Write and read a blob from GCS using file-like IO"""
    # The ID of your GCS bucket
    # bucket_name = "your-bucket-name"

    # The ID of your new GCS object
    # blob_name = "storage-object-name"

    storage_client = storage.Client()
    bucket = storage_client.bucket(bucket_name)
    blob = bucket.blob(blob_name)

    # Mode can be specified as wb/rb for bytes mode.
    # See: https://docs.python.org/3/library/io.html
    with blob.open("w") as f:
        f.write("Hello world")

    with blob.open("r") as f:
        print(f.read())

다음에 유의하세요.

  • 쓰기 위해 파일을 열기 위한 호출에서 이 샘플은 파일의 커스텀 메타데이터를 쓰는 특정 Cloud Storage 헤더를 지정합니다. cloudstorage.stat()을 사용하여 이 메타데이터를 검색할 수 있습니다. cloudstorage.open() 참조 문서에서 지원되는 헤더 목록을 확인할 수 있습니다.

  • x-goog-acl 헤더가 설정되지 않았습니다. 즉, 기본 Cloud Storage ACL의 공개 읽기는 버킷에 기록될 때 객체에 적용됩니다.

  • 쓰기를 마친 후에는 파일을 닫는 함수를 호출해야 합니다. 그렇지 않으면 파일이 Cloud Storage에 기록되지 않습니다. Python 파일 함수 close()를 호출한 후에는 파일에 아무 것도 추가할 수 없습니다. 파일을 수정해야 하는 경우 Python 파일 함수 open()을 호출하여 쓰기 모드로 파일을 다시 열어야 하며, 이 경우 파일을 추가하지 않고 덮어씁니다.

Cloud Storage에서 읽기

다음 샘플은 버킷에서 전체 파일을 읽는 방법을 보여줍니다.

from google.cloud import storage

def write_read(bucket_name, blob_name):
    """Write and read a blob from GCS using file-like IO"""
    # The ID of your GCS bucket
    # bucket_name = "your-bucket-name"

    # The ID of your new GCS object
    # blob_name = "storage-object-name"

    storage_client = storage.Client()
    bucket = storage_client.bucket(bucket_name)
    blob = bucket.blob(blob_name)

    # Mode can be specified as wb/rb for bytes mode.
    # See: https://docs.python.org/3/library/io.html
    with blob.open("w") as f:
        f.write("Hello world")

    with blob.open("r") as f:
        print(f.read())

두 예시에서 cloudstorage.open()에 전달하는 blob_name 인수는 YOUR_BUCKET_NAME/PATH_IN_GCS 형식의 파일 경로입니다. cloudstorage.open()의 기본값은 읽기 전용 모드입니다. 파일을 읽기 위해 파일을 열 때 모드를 지정할 필요는 없습니다.

버킷 콘텐츠 나열

샘플 코드는 blob 유형 콘텐츠를 사용해서 버킷을 통해 페이징하는 방법을 보여줍니다.

from google.cloud import storage

def list_blobs(bucket_name):
    """Lists all the blobs in the bucket."""
    # bucket_name = "your-bucket-name"

    storage_client = storage.Client()

    # Note: Client.list_blobs requires at least package version 1.17.0.
    blobs = storage_client.list_blobs(bucket_name)

    # Note: The call returns a response only when the iterator is consumed.
    for blob in blobs:
        print(blob.name)

전체 파일 이름은 디렉터리 구분 기호 없이 문자열 하나로 표시됩니다. 보기 쉽게 디렉터리 계층 구조로 파일을 표시하려면 사용할 디렉터리 구분 기호로 delimiter 매개변수를 설정합니다.

Cloud Storage의 파일 삭제

아래 코드는 cloudstorage.delete() 메서드(gcs로 가져옴)를 사용하여 Cloud Storage에서 파일을 삭제하는 방법을 보여줍니다.

from google.cloud import storage

def delete_blob(bucket_name, blob_name):
    """Deletes a blob from the bucket."""
    # bucket_name = "your-bucket-name"
    # blob_name = "your-object-name"

    storage_client = storage.Client()

    bucket = storage_client.bucket(bucket_name)
    blob = bucket.blob(blob_name)
    generation_match_precondition = None

    # Optional: set a generation-match precondition to avoid potential race conditions
    # and data corruptions. The request to delete is aborted if the object's
    # generation number does not match your precondition.
    blob.reload()  # Fetch blob metadata to use in generation_match_precondition.
    generation_match_precondition = blob.generation

    blob.delete(if_generation_match=generation_match_precondition)

    print(f"Blob {blob_name} deleted.")

이 예는 Cloud Storage에 쓰기 섹션의 버킷에 기록된 파일을 정리합니다.

다음 단계