Skip to content

Instantly share code, notes, and snippets.

@muhammad-asn
Created December 18, 2024 23:15
Show Gist options
  • Save muhammad-asn/c4b5e6df6c9fcd5df5ca63657648cda1 to your computer and use it in GitHub Desktop.
Save muhammad-asn/c4b5e6df6c9fcd5df5ca63657648cda1 to your computer and use it in GitHub Desktop.
GCP Presigned URL bucket

GCS Signed URL Generator

This Python script generates a signed URL for downloading a blob from Google Cloud Storage (GCS). The signed URL allows users to access the blob without requiring authentication.

Prerequisites

  • Python >= 3.10.x
  • Google Service Account

How to Use

$ export GOOGLE_APPLICATION_CREDENTIALS="/path/to/your/service-account-file.json"
$ python3 gcs-sign.py -h
usage: gcs-sign.py [-h] -b BUCKET_NAME -o BLOB_NAME -e EXPIRATION

Generate a signed URL for a Google Cloud Storage blob.

options:
  -h, --help            show this help message and exit
  -b BUCKET_NAME, --bucket-name BUCKET_NAME
                        The name of the GCS bucket
  -o BLOB_NAME, --blob-name BLOB_NAME
                        The name of the blob in the bucket
  -e EXPIRATION, --expiration EXPIRATION
                        The expiration time in minutes for the signed URL
import datetime
import argparse
import logging
from google.cloud import storage
# Set up logging
logging.basicConfig(level=logging.INFO)
def generate_download_signed_url_v4(bucket_name: str, blob_name: str, expiration_minutes: int) -> str:
"""Generates a v4 signed URL for downloading a blob."""
try:
storage_client = storage.Client()
bucket = storage_client.bucket(bucket_name)
blob = bucket.blob(blob_name)
url = blob.generate_signed_url(
version="v4",
expiration=datetime.timedelta(minutes=expiration_minutes),
method="GET",
)
logging.info("Generated GET signed URL: %s", url)
return url
except Exception as e:
logging.error("Error generating signed URL: %s", e)
raise
if __name__ == "__main__":
parser = argparse.ArgumentParser(description='Generate a signed URL for a Google Cloud Storage blob.')
parser.add_argument('-b', '--bucket-name', type=str, required=True, help='The name of the GCS bucket')
parser.add_argument('-o', '--blob-name', type=str, required=True, help='The name of the blob in the bucket')
parser.add_argument('-e', '--expiration', type=int, required=True, help='The expiration time in minutes for the signed URL')
args = parser.parse_args()
# Set logging level based on the verbose flag or log-level flag
if args.verbose:
logging.basicConfig(level=logging.DEBUG)
else:
logging.basicConfig(level=args.log_level)
url = generate_download_signed_url_v4(args.bucket_name, args.blob_name, args.expiration)
print(url)
google-cloud-storage==2.19.0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment