快速入门:使用 Python v2.1 SDK 管理 blobQuickstart: Manage blobs with Python v2.1 SDK

本快速入门介绍如何使用 Python 管理 blob。In this quickstart, you learn to manage blobs by using Python. Blob 是可以保存大量文本或二进制数据(包括图像、文档、流媒体和存档数据)的对象。Blobs are objects that can hold large amounts of text or binary data, including images, documents, streaming media, and archive data. 你将上传、下载和列出 Blob,并创建和删除容器。You'll upload, download, and list blobs, and you'll create and delete containers.

备注

此快速启动使用 Azure Blob 存储客户端库的旧版本。This quickstart uses a legacy version of the Azure Blob storage client library. 若要开始使用最新版本,请参阅快速入门:使用 Python v12 SDK 管理 blobTo get started with the latest version, see Quickstart: Manage blobs with Python v12 SDK.

先决条件Prerequisites

备注

本文中所述的功能现在可用于具有分层命名空间的帐户。The features described in this article are now available to accounts that have a hierarchical namespace. 若要查看限制,请参阅 Azure Data Lake Storage Gen2 中可用的 Blob 存储功能一文。To review limitations, see the Blob storage features available in Azure Data Lake Storage Gen2 article.

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

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

使用以下 git 命令将应用程序下载到开发环境。Use the following git command to download the application to your development environment.

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

若要查看 Python 程序,请在存储库的根目录中打开 example.py 文件。To review 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 门户中转到自己的存储帐户。In to the Azure portal go to your storage account.

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

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

  4. 找到“key1”下面的“密钥”值,选择“复制”复制该帐户密钥。 Find the Key value under key1, and select Copy 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.

  1. 从 IDE 中的解决方案资源管理器打开 example.py 文件。Open the example.py file from the Solution Explorer in your IDE.

  2. accountnameaccountkey 值替换为自己的存储帐户名和密钥:Replace the accountname and accountkey values with your storage account name and key:

    block_blob_service = BlockBlobService(
        account_name='accountname', account_key='accountkey', endpoint_suffix='core.chinacloudapi.cn')
    
  3. 保存并关闭该文件。Save and close the file.

运行示例Run the sample

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

  1. 安装依赖项:Install the dependencies:

    pip install azure-storage-blob==2.1.0
    
  2. 转到示例应用程序:Go to the sample application:

    cd storage-blobs-python-quickstart
    
  3. 运行示例:Run the sample:

    python example.py
    

    会看到类似于以下输出的消息: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
    
  4. 继续操作前,请转到 Documents 文件夹,检查其中是否有这两个文件。Before you continue, go to your Documents folder and check for the two files.

    • QuickStart_<universally-unique-identifier>QuickStart_<universally-unique-identifier>
    • QuickStart_<universally-unique-identifier>_DOWNLOADEDQuickStart_<universally-unique-identifier>_DOWNLOADED
  5. 可以打开它们,看它们是否相同。You can open them and see they're the same.

    还可以使用工具,例如 Azure 存储资源管理器You can also use a tool like the Azure Storage Explorer. 它适用于查看 Blob 存储中的文件。It's good for viewing the files in Blob storage. Azure 存储资源管理器是免费的跨平台工具,用于访问存储帐户信息。Azure Storage Explorer is a free cross-platform tool that lets you access your storage account info.

  6. 查看文件后,按任意键可完成示例并删除测试文件。After you've looked at the files, press any key to finish the sample and delete the test files.

了解示例代码Learn about the sample code

了解此示例的用途以后,即可打开 example.py 文件来查看代码。Now that you know what the sample does, open the example.py file to look at the code.

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

此部分将实例化对象,新建容器,然后设置容器的权限,以便 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. 需调用容器 quickstartblobsYou'll call the container quickstartblobs.

# Create the BlockBlockService that the system uses 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 存储的对象的引用。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,就像使用计算机上的文件夹组织文件一样。The system uses containers 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.

重要

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

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

Blob 存储支持块 blob、追加 blob 和页 blob。Blob storage supports block blobs, append blobs, and page blobs. 块 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 用于日志记录。You can use append blobs for logging when you want to write to a file and then keep adding more information. 页 Blob 主要用于虚拟硬盘 (VHD) 文件,这些文件支持基础结构即服务虚拟机 (IaaS VM)。Page blobs are primarily used for the Virtual Hard Disk (VHD) files that back infrastructure as a service virtual machines (IaaS VMs). 块 blob 是最常用的。Block blobs are the most commonly used. 本快速入门使用块 Blob。This quickstart uses block blobs.

若要将文件上传到 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 the system uses for the upload and download, storing the file the system uploads as full_path_to_file and the name of the blob as local_file_name. 此示例将文件上传到名为 quickstartblobs 的容器:This 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.

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

以下代码为 list_blobs 方法创建 generatorThe following code creates a generator for the list_blobs method. 此代码循环访问容器中的 Blob 列表,并将其名称输出到控制台。The code loops through the list of blobs in the container and prints their names to the console.

# 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 you uploaded previously. 系统将“_DOWNLOADED”追加到 Blob 名称,因此可以在本地磁盘上看到这两个文件。The system appends _DOWNLOADED to the blob name so you can see both files on your 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, local_file_name.replace(
   '.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 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,请参阅使用存储资源管理器管理 Azure Blob 存储资源For more about the Storage Explorer and Blobs, see Manage Azure Blob storage resources with Storage Explorer.