Create Pre-Signed URLs - Cloud Storage
Creating pre-signed URLs varies slightly between different cloud storage services. Below are examples for Amazon S3, Google Cloud Storage, and Azure Blob Storage:
Amazon S3
For Amazon S3, you can use the AWS SDK for Python (Boto3) to generate pre-signed URLs. Below is an example:
pythonimport boto3 from botocore.exceptions import NoCredentialsError def create_presigned_url(bucket_name, object_name, expiration=300): s3_client = boto3.client('s3') try: response = s3_client.generate_presigned_url('get_object', Params={'Bucket': bucket_name, 'Key': object_name}, ExpiresIn=expiration) except NoCredentialsError: print("No credentials available") return None return response
This script generates a pre-signed URL that will remain valid for 5 minutes (300 seconds).
Google Cloud Storage
For Google Cloud Storage, you can use the Google Cloud SDK for Python to generate pre-signed URLs. Here is an example:
pythonfrom google.cloud import storage import datetime def generate_download_signed_url_v4(bucket_name, blob_name): 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=5), method="GET") return url
This script generates a v4 pre-signed URL for downloading a blob. The URL will remain valid for 5 minutes.
Azure Blob Storage
For Azure Blob Storage, you can use the Azure Storage SDK for Python to generate pre-signed URLs. Below is an example:
pythonfrom azure.storage.blob import BlobServiceClient, BlobSasPermissions, generate_blob_sas from datetime import datetime, timedelta def generate_sas_url(account_name, account_key, container_name, blob_name): blob_service_client = BlobServiceClient(account_url=f"https://{account_name}.blob.core.windows.net", credential=account_key) sas_token = generate_blob_sas( blob_service_client.account_name, container_name, blob_name, account_key=account_key, permission=BlobSasPermissions(read=True), expiry=datetime.utcnow() + timedelta(minutes=5) ) return f"https://{account_name}.blob.core.windows.net/{container_name}/{blob_name}?{sas_token}"
This script generates a SAS URL that will remain valid for 5 minutes.
Remember to replace the placeholders (bucket_name
, object_name
etc.) with your actual bucket details and file path.
Also, for all the examples to work, you must have the necessary credentials configured in your environment.