Search code examples
azure-blob-storageblobazure-python-sdk

What is the blob_name for Azure generate_blob_sas() Python SDK, when folder paths are involved?


I'd like to generate_blob_sas using the Azure Python SDK.

The blob URL looks something like this: https://<account_name>.blob.core.windows.net/<container_name>/<folder_1>/<folder_2>/<blob_name>.jpg

The snippet in question looks something like this:

# Generate SAS token
blob_sas_token = generate_blob_sas(
    account_name = storage_account_name,
    container_name = storage_container_name,
    blob_name = "",
    account_key = storage_account_key,
    permission = BlobSasPermissions.from_string(TOKEN_PERMISSIONS),
    expiry = datetime.utcnow() + timedelta(minutes=TOKEN_DURATION_MINUTES)
)

Question:

  • Does the blob_name consist of <folder_1>/<folder_2>/<blob_name>.jpg? OR
  • Does the blob_name consist only of <blob_name>.jpg?

Solution

    • Does the blob_name consist of <folder_1>/<folder_2>/<blob_name>.jpg? OR Does the blob_name consist only of <blob_name>.jpg?

    I agree with @Gauravmantri, you need to use the blob name with path <folder_1>/<folder_2>/<blob_name>.jpg.

    Here is workaround for the generate sas token with blob name using python:

    Code:

    from datetime import datetime, timedelta
    from azure.storage.blob import generate_blob_sas, BlobSasPermissions
    
    # Set the storage account details
    storage_account_name = "venkat123"
    storage_account_key = "accountkey"
    storage_container_name = "test"
    blob_name = "folder1/subfolder1/image1.png"
    
    # Set the SAS token parameters
    sas_expiry = datetime.utcnow() + timedelta(hours=1)
    sas_permissions = BlobSasPermissions(read=True, write=True)
    
    # Generate SAS token for the blob
    blob_sas_token = generate_blob_sas(
        account_name=storage_account_name,
        container_name=storage_container_name,
        blob_name=blob_name,
        account_key=storage_account_key,
        permission=sas_permissions,
        expiry=sas_expiry
    )
    
    # Construct the full URL with the SAS token
    blob_url_with_sas = f"https://{storage_account_name}.blob.core.windows.net/{storage_container_name}/{blob_name}?{blob_sas_token}"
    
    print("Blob URL with SAS token:")
    print(blob_url_with_sas)
    

    Output:

    Blob URL with SAS token:
    https://<storage account name>.blob.core.windows.net/test/folder1/subfolder1/image1.png?<SAS token>
    

    enter image description here

    Browser: enter image description here