Lettura e scrittura in Cloud Storage

Questo documento descrive come archiviare e recuperare i dati utilizzando la libreria client Cloud Storage. Presuppone che tu abbia completato le attività descritte in Configurazione per Cloud Storage per attivare un bucket Cloud Storage e scaricare le librerie client. Inoltre, presuppone che tu sappia come creare un'applicazione App Engine.

Per ulteriori esempi di codice, consulta Librerie client di Cloud Storage .

Importazioni richieste

Utilizza lo snippet di codice riportato di seguito per accedere a Cloud Storage utilizzando la libreria client:

# 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.")

Specificare il bucket Cloud Storage

Prima di eseguire qualsiasi operazione in Cloud Storage, devi fornire il nome del bucket.

# 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.")

Il modo più semplice per specificare un nome del bucket è utilizzare il bucket predefinito per il progetto. La chiamata a get_default_gcs_bucket_name ha esito positivo solo se hai creato il bucket predefinito per il tuo progetto.

Scrittura in Cloud Storage

Il seguente esempio mostra come scrivere nel bucket:

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

Tieni presente quanto segue:

  • Nella chiamata per aprire il file in scrittura, l'esempio specifica determinate intestazioni Cloud Storage che scrivono metadati personalizzati per il file; questi metadati possono essere recuperati utilizzando cloudstorage.stat(). Puoi trovare l'elenco delle intestazioni supportate nel riferimento cloudstorage.open().

  • L'intestazione x-goog-acl non è impostata. Ciò significa che l'ACL Cloud Storage predefinita di lettura pubblica verrà applicata all'oggetto quando viene scritto nel bucket.

  • Assicurati di richiamare la funzione per chiudere il file dopo aver terminato la scrittura. Se non lo fai, il file non viene scritto in Cloud Storage. Tieni presente che dopo aver chiamato la funzione del file Python close(), non puoi aggiungere elementi al file. Se devi modificare un file, dovrai chiamare la funzione del file Python open() per aprire nuovamente il file in modalità di scrittura, che esegue una sovrascrittura, non un'aggiunta.

Lettura da Cloud Storage

L'esempio seguente mostra come leggere un file completo dal bucket:

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

In entrambi gli esempi, l'argomento blob_name che passi a cloudstorage.open() è il percorso del file in formato YOUR_BUCKET_NAME/PATH_IN_GCS. Tieni presente che la modalità di sola lettura è l'impostazione predefinita per cloudstorage.open(). Non devi specificare una modalità quando apri un file per leggerlo.

Elenco dei contenuti del bucket

Il codice campione mostra come scorrere le pagine di un bucket con contenuti di tipo 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)

Tieni presente che il nome file completo viene visualizzato come una stringa senza delimitatori di directory. Se vuoi visualizzare il file con la gerarchia di directory più riconoscibile, imposta il parametro delimiter sul delimitatore di directory che vuoi utilizzare.

Eliminazione di file in Cloud Storage

Il codice riportato di seguito mostra come eliminare un file da Cloud Storage utilizzando il metodo cloudstorage.delete() (importato come gcs).

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.")

Questo esempio pulisce i file scritti nel bucket nella sezione Scrittura in Cloud Storage.

Passaggi successivi