Lettura e scrittura in Cloud Storage

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

Per ulteriori esempi di codice, consulta librerie client di Cloud Storage

Importazioni obbligatorie

Utilizza lo snippet di codice riportato di seguito per accedere a Cloud Storage mediante 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.")

Specifica del 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 il nome di un bucket è utilizzare il bucket predefinito per il tuo progetto. La chiamata a get_default_gcs_bucket_name ha esito positivo solo se hai creato il bucket predefinito per il 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 per la scrittura, l'esempio specifica alcune 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 predefinito di public read verrà applicato all'oggetto quando viene scritto nel bucket.

  • Assicurati di richiamare la funzione per chiudere il file al termine della 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, devi chiamare la funzione file Python open() per riaprire il file in modalità di scrittura, eseguendo la sovrascrittura, non un'aggiunta.

Lettura da Cloud Storage

Il seguente esempio 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 l'impostazione predefinita per cloudstorage.open() è la modalità di sola lettura. Non è necessario specificare una modalità quando si apre un file per leggerlo.

Elenco dei contenuti del bucket

Il codice campione mostra come navigare in 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 completo del file viene visualizzato come una stringa senza delimitatori di directory. Se vuoi visualizzare il file con una gerarchia di directory più riconoscibile, imposta il parametro delimiter sul delimitatore di directory che vuoi utilizzare.

Eliminazione di file in Cloud Storage

Il codice seguente 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 esegue la pulizia dei file scritti nel bucket nella sezione Scrittura in Cloud Storage.

Passaggi successivi