Google provides Cloud Client Libraries for accessing Cloud APIs programmatically,
google-cloud-storage
is the client library for accessing Cloud storage services. In this tutorial we will see, how to create
create cloud storage bucket and list objects of bucket with Python
.
Pre-requisite for executing below code is to have a service account with Storage Admin
role,
refer How to create service account
in GCPto create service account and downloading the json key.
pip install google-cloud-storage
from google.cloud import storage
import os
# Provide path for service accounts keys for authentication
os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = r"C:\Users\****\Desktop\keys.json"
# Instantiates a client
storage_client = storage.Client()
my_bucket_name = "[my-bucket-name]" # Replace [my-bucket-name] with actual bucket name
bucket = storage_client.create_bucket(my_bucket_name)
msg = f"Bucket with name {bucket.name} has been created"
print(msg)
Upload few images or text files in the newly bucket from Cloud console, for this tutorial few images were uploaded in the newly create bucket.
object_generator = storage_client.list_blobs(my_bucket_name)
for i in object_generator:
print(i)
<Blob: [my-bucket-name], flower.jpg, 1588604065075004>
<Blob: [my-bucket-name], mountains.jpg, 1588604070602145>
<Blob: [my-bucket-name], sample.jpg, 1588604081103677>
Similar Articles