Lettura e scrittura su Cloud Storage

Questo documento descrive come archiviare e recuperare i dati utilizzando libreria client di Cloud Storage. Presuppone che tu abbia completato le attività descritto in Configurazione di Cloud Storage per attivare un'istanza Cloud Storage nel bucket 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 obbligatorie

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

Specifica il bucket Cloud Storage

Prima di eseguire qualsiasi operazione in Cloud Storage, devi fornire il 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 di bucket è utilizzare il bucket predefinito per il progetto. La chiamata a get_default_gcs_bucket_name riesce solo se hai creato il bucket predefinito per il tuo progetto.

Scrittura in Cloud Storage

L'esempio seguente 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 Intestazioni Cloud Storage che scrivono metadati personalizzati per il file; questo i metadati possono essere recuperati utilizzando cloudstorage.stat(). Puoi trovare l'elenco supportate nel riferimento di cloudstorage.open().

  • L'intestazione x-goog-acl non è impostata. Ciò significa che il Cloud Storage predefinito L'ACL di lettura pubblica verrà applicato a dell'oggetto quando viene scritto nel bucket.

  • Assicurati di richiamare la funzione per chiudere il file al termine della scrittura. Se non farlo, il file non viene scritto in Cloud Storage. Ricorda che dopo il chiami la funzione file Python close(), non puoi aggiungerla al file. Se devi modificare un file, devi chiamare la funzione file Python open() per riaprire il file in modalità di scrittura, operazione 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 YOUR_BUCKET_NAME/PATH_IN_GCS. Nota che l'impostazione predefinita per cloudstorage.open() è la modalità di sola lettura. Non devi è necessario specificare una modalità all'apertura di 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 file completo viene visualizzato come una stringa senza directory delimitatori. Se vuoi visualizzare il file con la sua directory più riconoscibile gerarchia, imposta il parametro delimiter sul delimitatore di directory che vuoi per gli utilizzi odierni.

Eliminazione di file in Cloud Storage

Il codice seguente mostra come eliminare un file da Cloud Storage utilizzando 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 Sezione Scrittura in Cloud Storage.

Passaggi successivi