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 の public read がそのオブジェクトに適用されます。

  • 書き込みが完了したら、必ず、ファイルを閉じる関数を呼び出してください。これを行わないと、ファイルは 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)

完全なファイル名が、ディレクトリ区切り記号なしで 1 つの文字列として表示されていることに注意してください。わかりやすいディレクトリ階層でファイルを表示させる場合は、使用するディレクトリ区切り記号を 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 に書き込むセクションでバケットに書き込んだファイルをクリーンアップしています。

次のステップ