如何使用Azure Blob存储SDK将Blob从一个容器复制到另一个容器 [英] How to copy a blob from one container to another container using Azure Blob storage SDK
问题描述
我一直在参考文档 https://docs.microsoft.com/zh-CN/azure/storage/blobs/storage-quickstart-blobs-python .我无法找到用于将文件从一个容器复制/移动到另一个容器的正确API.假设我有两个容器A和B.现在我要将一个Blob从A复制到B.如何实现呢?一个例子,将不胜感激.
I have been referring to the document https://docs.microsoft.com/en-us/azure/storage/blobs/storage-quickstart-blobs-python. I have not been able to find the proper APIs for copy/move a file from one container to another container. Let's say I have two containers A and B. Now I want to copy a blob from A to B. How can I achieve this? An example will be appreciated.
azure-core==1.1.1
azure-storage-blob==12.0.0
Note: I have been through this thread which is supported only in older version of the SDK.
推荐答案
以下是SDK的 12.0.0 版本的完整示例:
Here's a full example for version 12.0.0 of the SDK:
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)
请参见此处有关如何获取容器的连接字符串和访问密钥的更多信息.
See here for more information on how you can get the connection string and access key for the container.
此答案假定两个容器都在同一预订中.
This answer assumes that both containers are within the same subscription.
这篇关于如何使用Azure Blob存储SDK将Blob从一个容器复制到另一个容器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!