Google Cloud Storage Examples

What is a Google Cloud Storage bucket?

A Google storage bucket is a cloud location where files can be saved within a Google Cloud project. More information on Google buckets can be found here.

Some specific notes on naming the bucket: - Every bucket name must be unique. - Bucket names are publicly visible. - Spaces are not allowed. - The full list of requirements is available here.

Setting up access on a local machine

Folow the steps from the links below, depending on your operating system:

Google Cloud Storage client libraries

Installation for Python

To install the Google Cloud Storage API for Python, run the following in a command prompt:

  • pip install --upgrade google-cloud-storage

  • gcloud init

Cloud Storage functions

[1]:
# Imports the Google Cloud client library
from google.cloud import storage
[2]:
# Create a new bucket
def create_new_bucket(bucket_name):
    """Create a new Google Cloud storage bucket."""
    # Instantiates a Google Storage client
    storage_client = storage.Client()

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

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

    print("Bucket {} created.".format(bucket.name))
[3]:
# List items in bucket
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)

    for blob in blobs:
        print(blob.name)

[4]:
# Download items from bucket
def download_blob(bucket_name, source_blob_name, destination_file_name):
    """Downloads a blob from the bucket."""
    # bucket_name = "your-bucket-name"
    # source_blob_name = "storage-object-name"
    # destination_file_name = "local/path/to/file"

    storage_client = storage.Client()

    bucket = storage_client.bucket(bucket_name)

    # Construct a client side representation of a blob.
    # Note `Bucket.blob` differs from `Bucket.get_blob` as it doesn't retrieve
    # any content from Google Cloud Storage. As we don't need additional data,
    # using `Bucket.blob` is preferred here.
    blob = bucket.blob(source_blob_name)
    blob.download_to_filename(destination_file_name)

    print(
        "Blob {} downloaded to {}.".format(
            source_blob_name, destination_file_name
        )
    )