快速入门:使用 Python 上传、下载和列出 BlobQuickstart: Upload, download, and list blobs with Python

本快速入门介绍如何使用 Python 上传、下载和列出 Azure Blob 存储的容器中的块 Blob。In this quickstart, you see how to use Python to upload, download, and list block blobs in a container in Azure Blob storage. Blob 是简单的对象,可以保留任何数量的文本或二进制数据(例如图像、文档、流媒体、存档数据等),并在文件共享、无架构表格和消息队列方面与 Azure 存储有所不同。Blobs are simply objects that can hold any amount of text or binary data (such as images, documents, streaming media, archive data, etc.), and are distinct in Azure Storage from file shares, schemaless tables, and message queues. (有关详细信息,请参阅 Azure 存储简介。)(For more information, see Introduction to Azure Storage.)

先决条件Prerequisites

若要访问 Azure 存储,需要一个 Azure 订阅。To access Azure Storage, you'll need an Azure subscription. 如果还没有订阅,则在开始前创建一个 1 元人民币的试用帐户If you don't already have a subscription, then create a 1rmb trial account before you begin.

对 Azure 存储进行的所有访问都要通过存储帐户完成。All access to Azure Storage takes place through a storage account. 对于本快速入门,请使用 Azure 门户、Azure PowerShell 或 Azure CLI 创建存储帐户。For this quickstart, create a storage account using the Azure portal, Azure PowerShell, or Azure CLI. 有关如何创建帐户的帮助,请参阅创建存储帐户For help creating the account, see Create a storage account.

请确保已安装下述额外的必备组件:Make sure you have the following additional prerequisites installed:

下载示例应用程序Download the sample application

本快速入门中的示例应用程序是基本的 Python 应用程序。The sample application in this quickstart is a basic Python application.

使用 git 可将应用程序的副本下载到开发环境。Use git to download a copy of the application to your development environment.

git clone https://github.com/Azure-Samples/storage-blobs-python-quickstart.git 

此命令会将 Azure-Samples/storage-blobs-python-quickstart 存储库克隆到本地 git 文件夹。This command clones the Azure-Samples/storage-blobs-python-quickstart repository to your local git folder. 若要运行 Python 程序,请在存储库的根目录中打开 example.py 文件。To run the Python program, open the example.py file at the root of the repository.

从 Azure 门户复制凭据Copy your credentials from the Azure portal

此示例应用程序需要对存储帐户访问进行授权。The sample application needs to authorize access to your storage account. 以连接字符串形式将存储帐户凭据提供给应用程序。Provide your storage account credentials to the application in the form of a connection string. 若要查看存储帐户凭据,请执行以下操作:To view your storage account credentials:

  1. 导航到 Azure 门户Navigate to the Azure portal.

  2. 找到自己的存储帐户。Locate your storage account.

  3. 在存储帐户概述的“设置”部分,选择“访问密钥”。In the Settings section of the storage account overview, select Access keys. 将显示你的帐户访问密钥和连接字符串。Your account access keys and connection string are displayed.

  4. 请记下存储帐户的名称,进行授权时,需提供该名称。Note the name of your storage account, which you'll need for authorization.

  5. 找到“key1”下面的“密钥”值,单击“复制”按钮复制该帐户密钥。Find the Key value under key1, and click the Copy button to copy the account key.

    显示如何从 Azure 门户复制帐户密钥的屏幕截图

配置存储连接字符串Configure your storage connection string

在应用程序中,请提供存储帐户名称和帐户密钥,以创建 BlockBlobService 对象。In the application, provide your storage account name and account key to create a BlockBlobService object. 从 IDE 中的解决方案资源管理器打开 example.py 文件。Open the example.py file from the Solution Explorer in your IDE. 连接到中国云时,将 accountnameaccountkey 值替换为自己的帐户名称和密钥,并添加 endpoint_suffix 值。Replace the accountname and accountkey values with your account name and key,and add endpoint_suffix value when connecting to the China cloud.

block_blob_service = BlockBlobService(account_name='accountname', account_key='accountkey', endpoint_suffix='core.chinacloudapi.cn') 

运行示例Run the sample

此示例在 Documents 文件夹中创建一个测试文件。This sample creates a test file in the Documents folder. 示例程序会将该测试文件上传到 Blob 存储,列出容器中的 blob,并使用新名称下载此文件。The sample program uploads the test file to Blob storage, lists the blobs in the container, and downloads the file with a new name.

首先,通过运行 pip install 安装依赖项:First, install the dependencies by running pip install:

    pip install azure-storage-blob

接下来,运行示例。Next, run the sample. 你将看到类似于以下输出的消息:You�ll see messages similar to the following output:

Temp file = C:\Users\azureuser\Documents\QuickStart_9f4ed0f9-22d3-43e1-98d0-8b2c05c01078.txt

Uploading to Blob storage as blobQuickStart_9f4ed0f9-22d3-43e1-98d0-8b2c05c01078.txt

List blobs in the container
         Blob name: QuickStart_9f4ed0f9-22d3-43e1-98d0-8b2c05c01078.txt

Downloading blob to C:\Users\azureuser\Documents\QuickStart_9f4ed0f9-22d3-43e1-98d0-8b2c05c01078_DOWNLOADED.txt

继续前,请在 Documents 文件夹中查看这两个文件。Before you continue, look in your Documents folder for the two files. 可以打开它们,看它们是否相同。You can open them and see they're the same.

还可以使用工具(如 Azure 存储资源管理器)查看 Blob 存储中的文件。You can also use a tool such as the Azure Storage Explorer to view the files in Blob storage. Azure 存储资源管理器是免费的跨平台工具,可用于访问存储帐户信息。Azure Storage Explorer is a free cross-platform tool that allows you to access your storage account information.

验证文件后,按任意键可完成演示并删除测试文件。After you've verified the files, press any key to finish the demo and delete the test files. 了解此示例的用途以后,即可打开 example.py 文件来查看代码。Now that you know what the sample does, open the example.py file to look at the code.

了解示例代码Understand the sample code

让我们逐步查看示例代码,了解其工作方式。Let's walk through the sample code to understand how it works.

获取对存储对象的引用Get references to the storage objects

首先,请创建对用于访问和管理 Blob 存储的对象的引用。First, you create the references to the objects used to access and manage Blob storage. 这些对象相互关联,并且每个对象被列表中的下一个对象使用。These objects build on each other, and each is used by the next one in the list.

  • 实例化 BlockBlobService 对象,该对象指向存储帐户中的 Blob 服务 。Instantiate the BlockBlobService object, which points to the Blob service in your storage account.

  • 实例化 CloudBlobContainer 对象,该对象代表你正在访问的容器 。Instantiate the CloudBlobContainer object, which represents the container you're accessing. 容器用于组织 blob,就像使用计算机上的文件夹组织文件一样。Containers are used to organize your blobs like you use folders on your computer to organize your files.

有了云 Blob 容器后,请实例化 CloudBlockBlob 对象(该对象指向你感兴趣的特定 Blob) 。Once you have the Cloud Blob container, instantiate the CloudBlockBlob object that points to the specific blob that you're interested in. 然后即可根据需要上传、下载和复制 Blob。You can then upload, download, and copy the blob as you need.

Important

容器名称必须为小写。Container names must be lowercase. 有关容器名称和 Blob 名称的详细信息,请参阅 命名和引用容器、Blob 和元数据For more information about container and blob names, see Naming and referencing Containers, Blobs, and Metadata.

此部分将实例化对象,新建容器,然后设置容器的权限,以便 blob 成为公共 blob。In this section, you instantiate the objects, create a new container, and then set permissions on the container so the blobs are public. 容器名称为 quickstartblobs 。The container is called quickstartblobs.

# Create the BlockBlockService that is used to call the Blob service for the storage account.
block_blob_service = BlockBlobService(account_name='accountname', account_key='accountkey', endpoint_suffix='core.chinacloudapi.cn')

# Create a container called 'quickstartblobs'.
container_name = 'quickstartblobs'
block_blob_service.create_container(container_name)

# Set the permission so the blobs are public.
block_blob_service.set_container_acl(container_name, public_access=PublicAccess.Container)

将 blob 上传到容器Upload blobs to the container

Blob 存储支持块 blob、追加 blob 和页 blob。Blob storage supports block blobs, append blobs, and page blobs. 块 blob 最常用,此快速入门中也使用块 blob。Block blobs are the most commonly used, and that's what is used in this quickstart.

若要将文件上传到 Blob,请通过将本地驱动器上的目录名称和文件名称联接在一起来获取完整的文件路径。To upload a file to a blob, get the full file path by joining the directory name with the file name on your local drive. 然后可以使用 create_blob_from_path 方法将文件上传到指定的路径。You can then upload the file to the specified path using the create_blob_from_path method.

示例代码将创建一个本地文件,以供上传和下载,并将要上传的此文件存储为 full_path_to_file ,将 blob 的名称存储为 local_file_name 。The sample code creates a local file to be used for the upload and download, storing the file to be uploaded as full_path_to_file and the name of the blob as local_file_name. 以下示例将文件上传到名为“quickstartblobs”的容器 。The following example uploads the file to your container called quickstartblobs.

# Create a file in Documents to test the upload and download.
local_path = os.path.expanduser("~\Documents")
local_file_name = "QuickStart_" + str(uuid.uuid4()) + ".txt"
full_path_to_file = os.path.join(local_path, local_file_name)

# Write text to the file.
file = open(full_path_to_file, 'w')
file.write("Hello, World!")
file.close()

print("Temp file = " + full_path_to_file)
print("\nUploading to Blob storage as blob" + local_file_name)

# Upload the created file, use local_file_name for the blob name.
block_blob_service.create_blob_from_path(container_name, local_file_name, full_path_to_file)

Blob 存储支持多种上传方法。There are several upload methods that you can use with Blob storage. 例如,若有一个内存流,则可使用 create_blob_from_stream 方法而不是 create_blob_from_path 方法。For example, if you have a memory stream, you can use the create_blob_from_stream method rather than create_blob_from_path.

块 blob 最大可以为 4.7 TB,并且可以是从 Excel 电子表格到大视频文件的任何内容。Block blobs can be as large as 4.7 TB, and can be anything from Excel spreadsheets to large video files. 页 Blob 主要用于支持 IaaS VM 的 VHD 文件。Page blobs are primarily used for the VHD files that back IaaS VMs. 追加 blob 用于日志记录,例如有时需要写入到文件,再继续添加更多信息。Append blobs are used for logging, such as when you want to write to a file and then keep adding more information. 存储在 Blob 存储中的大多数对象都是块 blob。Most objects stored in Blob storage are block blobs.

列出容器中的 BlobList the blobs in a container

使用 list_blobs 方法获取容器中文件的列表。Get a list of files in the container with the list_blobs method. 此方法会返回一个生成器。This method returns a generator. 下面的代码检索 Blob 列表,然后循环访问它们,显示在容器中找到的 Blob 的名称。The following code retrieves the list of blobs—then loops through them—showing the names of the blobs found in a container.

# List the blobs in the container.
print("\nList blobs in the container")
generator = block_blob_service.list_blobs(container_name)
for blob in generator:
    print("\t Blob name: " + blob.name)

下载 BlobDownload the blobs

使用 get_blob_to_path 方法将 Blob 下载到本地磁盘。Download blobs to your local disk using the get_blob_to_path method. 以下代码将下载前面部分所上传的 blob。The following code downloads the blob uploaded in a previous section. _DOWNLOADED 添加为 Blob 名称的前缀后,就可以在本地磁盘上同时看到这两个文件。_DOWNLOADED is added as a suffix to the blob name so you can see both files on local disk.

# Download the blob(s).
# Add '_DOWNLOADED' as prefix to '.txt' so you can see both files in Documents.
full_path_to_file2 = os.path.join(local_path, string.replace(local_file_name, '.txt', '_DOWNLOADED.txt'))
print("\nDownloading blob to " + full_path_to_file2)
block_blob_service.get_blob_to_path(container_name, local_file_name, full_path_to_file2)

清理资源Clean up resources

如果不再需要本快速入门中上传的 Blob,可使用 delete_container 方法删除整个容器。If you no longer need the blobs uploaded in this quickstart, you can delete the entire container using the delete_container method. 若要改为删除单个文件,请使用 delete_blob 方法。To delete individual files instead, use the delete_blob method.

# Clean up resources. This includes the container and the temp files.
block_blob_service.delete_container(container_name)
os.remove(full_path_to_file)
os.remove(full_path_to_file2)

用于开发包含 Blob 的 Python 应用程序的资源Resources for developing Python applications with blobs

若要详细了解如何使用 Blob 存储进行 Python 开发,请参阅下述额外资源:For more information about Python development with Blob storage, see these additional resources:

二进制文件和源代码Binaries and source code

客户端库参考和示例Client library reference and samples

后续步骤Next steps

本快速入门介绍了如何使用 Python 在本地磁盘和 Azure Blob 存储之间传输文件。In this quickstart, you learned how to transfer files between a local disk and Azure Blob storage using Python. 要深入了解如何使用 Blob 存储,请继续学习 Blob 存储操作说明。To learn more about working with Blob storage, continue to the Blob storage How-to.

若要详细了解存储资源管理器和 Blob,请参阅使用存储资源管理器管理 Azure Blob 存储资源For more information about the Storage Explorer and Blobs, see Manage Azure Blob storage resources with Storage Explorer.