以下示例将 Blob 下载到一个文件路径:
def download_blob_to_file(self, blob_service_client: BlobServiceClient, container_name):
blob_client = blob_service_client.get_blob_client(container=container_name, blob="sample-blob.txt")
with open(file=os.path.join('filepath', 'filename'), mode="wb") as sample_blob:
download_stream = blob_client.download_blob()
sample_blob.write(download_stream.readall())
以下示例将 Blob 下载到一个流。 在此示例中,
StorageStreamDownloader.read_into
将 blob 内容下载到一个流并返回读取的字节数:
def download_blob_to_stream(self, blob_service_client: BlobServiceClient, container_name):
blob_client = blob_service_client.get_blob_client(container=container_name, blob="sample-blob.txt")
# readinto() downloads the blob contents to a stream and returns the number of bytes read
stream = io.BytesIO()
num_bytes = blob_client.download_blob().readinto(stream)
print(f"Number of bytes: {num_bytes}")
在区块中下载 Blob
以下示例下载 Blob 并循环访问下载流中的区块。 在此示例中,
StorageStreamDownloader.chunks
返回一个迭代器,这允许你在区块中读取 blob 内容:
def download_blob_chunks(self, blob_service_client: BlobServiceClient, container_name):
blob_client = blob_service_client.get_blob_client(container=container_name, blob="sample-blob.txt")
# This returns a StorageStreamDownloader
stream = blob_client.download_blob()
chunk_list = []
# Read data in chunks to avoid loading all into memory at once
for chunk in stream.chunks():
# Process your data (anything can be done here - 'chunk' is a byte array)
chunk_list.append(chunk)
下载到字符串
以下示例将 Blob 内容下载为文本。 在此示例中,要想让
readall()
返回字符串,必须使用
encoding
参数,否则它将返回字节:
def download_blob_to_string(self, blob_service_client: BlobServiceClient, container_name):
blob_client = blob_service_client.get_blob_client(container=container_name, blob="sample-blob.txt")
# encoding param is necessary for readall() to return str, otherwise it returns bytes
downloader = blob_client.download_blob(max_concurrency=1, encoding='UTF-8')
blob_text = downloader.readall()
print(f"Blob contents: {blob_text}")
若要详细了解如何使用适用于 Python 的 Azure Blob 存储客户端库来下载 blob,请参阅以下资源。
REST API 操作
Azure SDK for Python 包含基于 Azure REST API 而生成的库,允许你通过熟悉的 Python 范例与 REST API 操作进行交互。 用于下载 blob 的客户端库方法使用以下 REST API 操作:
获取 Blob
(REST API)
查看本文中的代码示例 (GitHub)
客户端库资源
客户端库参考文档
客户端库源代码
包 (PyPi)