Search code examples
pythonazureexceptionblobstorage

How to break already present lease in azure python SDK


I have set the lease expiry to infinite because some of the blobs will be too large. I break the lease after the download. What I need is an exception that handles the lease already present error.

Function to download blobs which creates a lease that never expires

def save_blob(self, local_path, file_name, blob_client):
        """downloading blob to the respective folders"""
        
        # Get full path to the file
        download_file_path = os.path.join(local_path, file_name)
        Path(download_file_path).touch()
        # getting a lock on the blob using a lease that never expires
        lease = blob_client.acquire_lease(lease_duration=-1)

        with open(download_file_path, "wb") as file:
            data = blob_client.download_blob()
            data.download_to_stream(file)
        
        # breaking the lease after download
        lease.break_lease()

the try-except block

try:
    print(f"blob name in try: {blob.name}")
    self.save_blob(local_path, filename, blob_client)
    blob_count += 1
except: #if lease is already present
    blob_client.break_lease() # I need something like this
    self.save_blob(local_path, filename, blob_client)
    blob_count += 1

I read the doc on BlobLeaseClient which needs acquiring of lease to break a lease which we can't do because the lease is already there. I also tried to find the lease ID from the properties which was not there in properties dictionary.


Solution

  • You can make use of BlobLeaseClient to break the lease on an existing blob.

    Your code would be something like the following:

    blob_lease_client = BlobLeaseClient(blob_client)
    blob_lease_client.break_lease()