ANIVGames
ANIVGames

Reputation: 337

How to get URI of a blob in a google cloud storage (Python)

If I have a Blob object how can I get the URI (gs://...)?

The documentation says I can use self_link property to get the URI, but it returns the https URL instead (https://googleapis.com...) I am using python client library for cloud storage.

Thank you

Upvotes: 11

Views: 14520

Answers (2)

Illya Moskvin
Illya Moskvin

Reputation: 352

You can take the blob.id and chop off the generation from the end of it:

def get_blob_uri(blob):
    return 'gs://' + blob.id[:-(len(str(blob.generation)) + 1)]

Relevant docs:

Upvotes: 4

Chris32
Chris32

Reputation: 4961

Since you are not sharing with us how exactly are you trying to achieve this I did a quick script in Python to get this info

There is no specific method in blob to get the URI as gs:// in Python but you can try to script this by using the path_helper

def get_blob_URI():
    """Prints out a bucket's labels."""
    # bucket_name = 'your-bucket-name'
    storage_client = storage.Client()
    bucket_name = 'YOUR_BUCKET'
    blob_name = 'YOUR_OBJECT_NAME'
    bucket = storage_client.get_bucket(bucket_name)
    blob = bucket.blob(blob_name)
    link = blob.path_helper(bucket_name, blob_name)
    pprint.pprint('gs://' + link)

If you want to use the gsutil tool you can also get all the gs:// Uris of a bucket using the command gsutil ls gs://bucket

Upvotes: 8

Related Questions