Search code examples
pythonazureazure-blob-storageazure-storage-account

How to copy a file in Azure from a one storage account to another using Python?


I have written a piece of code to copy a file from one container to another within the same storage account.

  block_blob_service = BlockBlobService(
  account_name='', account_key='')

  blob_name = file_name
  copy_from_container = source
  copy_to_container = destination
  blob_url = block_blob_service.make_blob_url(copy_from_container, blob_name)
  # blob_url:https://demostorage.blob.core.windows.net/image-container/pretty.jpg
  block_blob_service.copy_blob(copy_to_container, blob_name, blob_url)

But now I want to copy files across different storage accounts. How can I do that?


Solution

  • Basically approach for copying a blob across storage accounts would remain more or less the same. You would need to do something like the following:

      source_block_blob_service = BlockBlobService(
      source_account_name= '', source_account_key= '')
    
      target_block_blob_service = BlockBlobService(
      target_account_name= '', target_account_key= '')
    
      blob_name = file_name
      copy_from_container = source
      copy_to_container = destination
      blob_url = source_block_blob_service.make_blob_url(copy_from_container, blob_name)
      # blob_url:https://demostorage.blob.core.windows.net/image-container/pretty.jpg
      target_block_blob_service.copy_blob(copy_to_container, blob_name, blob_url)
    

    Please note that when copying blob across storage account, the source blob URL should be publicly accessible. You can do so by either creating a Shared Access Signature (SAS) URL with at least read permission on the source blob (recommended approach) or make the ACL of source blob container (copy_from_container) as Blob (not recommended).