Get Google Cloud Storage Blob Url via Id/File path (Python)

March 5, 2020

Refer Setup Google Cloud Storage access (Python).

storage_client = None

DEFAULT_STORAGE_BUCKET_NAME = 'PROJECT_ID.appspot.com'

def init_storage():
    from google.cloud import storage

    global storage_client
    if storage_client:
        return storage_client

    # on cloud functions
    storage_client = storage.Client()
    # on external server
    # storage_client = storage.Client.from_service_account_json('keys/PROJECT_ID-storage.json')

    return storage_client
storage_client = init_storage()

gcs_id = 'gs://PROJECT_ID.appspot.com/DIRECTORY/FILENAME'

blob = Blob.from_string(gcs_id, client=storage_client)
blob_url = blob.generate_signed_url(expiration=timedelta(hours=1))

NOTE: Need Storage Admin permission to call Blob.generate_signed_url

This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.