How to delete blob using SAS token for folder

Dutta, Pijush 1 Reputation point
2024-07-31T17:34:19.62+00:00

Hi All,

I am using python SDK for my azure related operations. When I had container level permission for blob, I used the following code

def delete_blobs(asset_name, container_client, file_name, site_name, file_type):

if file_type == 'txt':

    blob_name_dir = f"container/Document/Chunks/{file_name}"

elif file_type == 'pdf':

    blob_name_dir = f"container/Document/Pages/{file_name}"

else:

    logger.info(f"Unsupported file type: {file_type}")

    return

blob_list = container_client.list_blobs(name_starts_with=blob_name_dir)

blob_to_delete = [blob.name for blob in blob_list if blob.name.startswith(blob_name_dir)]

for blob_name in blob_to_delete:

    logger.info(f"Deleting blob: {blob_name}")

    blob_client = container_client.get_blob_client(blob=blob_name)

    blob_client.delete_blob()

    logger.info("Blob got deleted")  

but now my container level permission is removed and SAS token is provided only for the folder

I am using BlobClient.from_blob_url method to access folder but cannot find any of the methods used a blob container. what is the way to search the blob files with starts with and also how can I delete as I am getting permission error for everything now

Azure Blob Storage
Azure Blob Storage
An Azure service that stores unstructured data in the cloud as blobs.
2,934 questions
{count} votes

2 answers

Sort by: Most helpful
  1. AzureAce 102 Reputation points
    2024-08-01T07:54:51.2466667+00:00

    Hi @Dutta, Pijush

    Thank you for posting this in Microsoft Q&A.

    You are facing a permission restriction where you can only access a specific folder in an Azure Blob Storage container using a SAS token. Your previous approach using container_client.list_blobs() is no longer feasible due to the limited permissions.

    Here’s a sample code snippet

    def delete_blobs(sas_token, container_name, folder_path, prefix=None):
        """Deletes blobs within a specified folder using a SAS token.
    
        Args:
            sas_token: The SAS token for the folder.
            container_name: The name of the container.
            folder_path: The path to the folder within the container.
            prefix: Optional prefix for filtering blobs.
        """
    
        base_url = f"https://{container_name}.blob.core.windows.net/{folder_path}"
        sas_url = f"{base_url}?{sas_token}"
    
        blob_client = BlobClient.from_blob_url(sas_url)
    
        blobs_to_delete = []
        for blob in blob_client.list_blobs_flat():
            if prefix and not blob.name.startswith(prefix):
                continue
            blobs_to_delete.append(blob.name)
    
        for blob_name in blobs_to_delete:
            blob_client = BlobClient.from_blob_url(f"{sas_url}/{blob_name}")
            blob_client.delete_blob()
    

    I hope this helps!
    Please mark as "Accept the answer" if the above steps helps you. Your suggestion will help others also!


  2. AzureAce 102 Reputation points
    2024-08-01T09:54:03.3766667+00:00

    Hi @Dutta, Pijush

    You can try this alternative approach.

    Iterating through hierarchical listings
    The list_blobs() offered by the BlobServiceClient or ContainerClient accepts a prefix argument. You can use this argument iteratively to navigate through the container hierarchy and list all blobs.

    Here's an example:

    def list_blobs_flat(container_client, prefix=""):
    #Lists all blobs recursively within a container (flattened)
    blobs = [] 
    for
    blobs.append(blob) 
    if
    blobs.extend(list_blobs_flat(container_client, blob.name + "/"))
    return blobs
    

    I hope this helps!
    Don't forget to "Accept the answer" if the above steps helps you. Your suggestion will help others also!

    Thanks


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.