python - 如何使用 Azure Blob 存储 SDK 将 Blob 从一个容器复制到另一个容器

标签 python azure azure-storage azure-blob-storage azure-sdk-python

我一直引用文档https://learn.microsoft.com/en-us/azure/storage/blobs/storage-quickstart-blobs-python 。我无法找到将文件从一个容器复制/移动到另一个容器的正确 API。假设我有两个容器 A 和 B。现在我想将一个 blob 从 A 复制到 B。我该如何实现呢?一个例子将不胜感激。

库详细信息:

azure-core==1.1.1
azure-storage-blob==12.0.0

注意:我已经经历过this thread仅旧版本的 SDK 支持。

最佳答案

以下是 SDK 版本 12.0.0 的完整示例:

from azure.storage.blob import BlobClient, BlobServiceClient
from azure.storage.blob import ResourceTypes, AccountSasPermissions
from azure.storage.blob import generate_account_sas    

connection_string = '' # The connection string for the source container
account_key = '' # The account key for the source container
source_container_name = '' # Name of container which has blob to be copied
blob_name = '' # Name of the blob you want to copy
destination_container_name = '' # Name of container where blob will be copied

# Create client
client = BlobServiceClient.from_connection_string(connection_string) 

# Create sas token for blob
sas_token = generate_account_sas(
    account_name = client.account_name,
    account_key = account_key 
    resource_types = ResourceTypes(object=True, container=True),
    permission= AccountSasPermission(read=True,list=True),
    start = datetime.now()
    expiry = datetime.utcnow() + timedelta(hours=4) # Token valid for 4 hours
)

# Create blob client for source blob
source_blob = BlobClient(
    client.url,
    container_name = source_container_name, 
    blob_name = blob_name,
    credential = sas_token
)

# Create new blob and start copy operation.
new_blob = client.get_blob_client(destination_container_name, blob_name)    
new_blob.start_copy_from_url(source_blob.url)

参见here有关如何获取容器的连接字符串和访问 key 的更多信息。

<小时/>

此答案假设两个容器位于同一订阅内。

关于python - 如何使用 Azure Blob 存储 SDK 将 Blob 从一个容器复制到另一个容器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59175743/

相关文章:

azure - 即使 URI 匹配,我仍收到 Azure 应用程序的 URI 重定向错误

.net - Azure Devops 管道和多项目 Docker

azure - 在SQL azure中引用blob存储数据

python - 使用 python re.compile 和 beautiful soup 来匹配字符串

python - Pyglet,播放器,下一首歌

python - 哪些因素导致数据无法在 python(或 python/node.js)的套接字中通过?

azure - 将 Azure 文件共享映射到 Azure Runbook 本地驱动器以用作临时存储

python - python中列表的高效缩减

azure - 如何使用azure逻辑应用程序内的文本检索选项集的整数值

django - 有选择地删除上传到 Azure blob 的图像(Django/Python 项目)