您现在访问的是微软AZURE全球版技术文档网站,若需要访问由世纪互联运营的MICROSOFT AZURE中国区技术文档网站,请访问 https://docs.azure.cn.

快速入门:使用 Python v12 SDK 管理 blobQuickstart: Manage blobs with Python v12 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.

其他资源:Additional resources:

先决条件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.

设置Setting up

本部分逐步指导如何准备一个项目,使其与适用于 Python 的 Azure Blob 存储客户端库 v12 配合使用。This section walks you through preparing a project to work with the Azure Blob storage client library v12 for Python.

创建项目Create the project

创建名为 blob-quickstart-v12 的 Python 应用程序。Create a Python application named blob-quickstart-v12.

  1. 在控制台窗口(例如 cmd、PowerShell 或 Bash)中,为项目创建新目录。In a console window (such as cmd, PowerShell, or Bash), create a new directory for the project.

    mkdir blob-quickstart-v12
    
  2. 切换到新创建的 blob-quickstart-v12 目录。Switch to the newly created blob-quickstart-v12 directory.

    cd blob-quickstart-v12
    
  3. 在 blob-quickstart-v12 目录中,创建名为 data 的另一个目录 。In side the blob-quickstart-v12 directory, create another directory called data. 将在这里创建和存储 blob 数据文件。This is where the blob data files will be created and stored.

    mkdir data
    

安装包Install the package

仍在应用程序目录中,使用 pip install 命令安装适用于 Python 包的 Azure Blob 存储客户端库。While still in the application directory, install the Azure Blob storage client library for Python package by using the pip install command.

pip install azure-storage-blob

此命令安装适用于 Python 包的 Azure Blob 存储客户端库及其依赖的所有库。This command installs the Azure Blob storage client library for Python package and all the libraries on which it depends. 在本例中,即适用于 Python 的 Azure Core 库。In this case, that is just the Azure core library for Python.

设置应用框架Set up the app framework

从项目目录中执行以下操作:From the project directory:

  1. 在代码编辑器中打开新文本文件Open a new text file in your code editor

  2. 添加 import 语句Add import statements

  3. 为程序创建结构,包括基本的异常处理Create the structure for the program, including basic exception handling

    代码如下:Here's the code:

    import os, uuid
    from azure.storage.blob import BlobServiceClient, BlobClient, ContainerClient
    
    try:
        print("Azure Blob storage v12 - Python quickstart sample")
        # Quick start code goes here
    except Exception as ex:
        print('Exception:')
        print(ex)
    
  4. 在 blob-quickstart-v12 目录中,将新文件另存为 blob-quickstart-v12.py 。Save the new file as blob-quickstart-v12.py in the blob-quickstart-v12 directory.

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

当示例应用程序向 Azure 存储发出请求时,必须对其进行授权。When the sample application makes a request to Azure Storage, it must be authorized. 若要对请求进行授权,请将存储帐户凭据以连接字符串形式添加到应用程序中。To authorize a request, add your storage account credentials to the application as a connection string. 按照以下步骤查看存储帐户凭据:View your storage account credentials by following these steps:

  1. 登录 Azure 门户Sign in to the Azure portal.

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

  3. 在存储帐户概述的“设置”部分,选择“访问密钥”。 In the Settings section of the storage account overview, select Access keys. 在这里,可以查看你的帐户访问密钥以及每个密钥的完整连接字符串。Here, you can view your account access keys and the complete connection string for each key.

  4. 找到“密钥 1”下面的“连接字符串”值,选择“复制”按钮复制该连接字符串。 Find the Connection string value under key1, and select the Copy button to copy the connection string. 下一步需将此连接字符串值添加到某个环境变量。You will add the connection string value to an environment variable in the next step.

    显示如何从 Azure 门户复制连接字符串的屏幕截图

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

复制连接字符串以后,请将其写入运行应用程序的本地计算机的新环境变量中。After you have copied your connection string, write it to a new environment variable on the local machine running the application. 若要设置环境变量,请打开控制台窗口,并遵照适用于操作系统的说明。To set the environment variable, open a console window, and follow the instructions for your operating system. <yourconnectionstring> 替换为实际的连接字符串。Replace <yourconnectionstring> with your actual connection string.

WindowsWindows

setx AZURE_STORAGE_CONNECTION_STRING "<yourconnectionstring>"

在 Windows 中添加环境变量后,必须启动命令窗口的新实例。After you add the environment variable in Windows, you must start a new instance of the command window.

LinuxLinux

export AZURE_STORAGE_CONNECTION_STRING="<yourconnectionstring>"

macOSmacOS

export AZURE_STORAGE_CONNECTION_STRING="<yourconnectionstring>"

重新启动程序Restart programs

添加环境变量后,重启需要读取环境变量的任何正在运行的程序。After you add the environment variable, restart any running programs that will need to read the environment variable. 例如,重启开发环境或编辑器,然后再继续。For example, restart your development environment or editor before continuing.

对象模型Object model

Azure Blob 存储最适合存储巨量的非结构化数据。Azure Blob storage is optimized for storing massive amounts of unstructured data. 非结构化数据是不遵循特定数据模型或定义的数据(如文本或二进制数据)。Unstructured data is data that does not adhere to a particular data model or definition, such as text or binary data. Blob 存储提供了三种类型的资源:Blob storage offers three types of resources:

  • 存储帐户The storage account
  • 存储帐户中的容器A container in the storage account
  • 容器中的 blobA blob in the container

以下图示显示了这些资源之间的关系。The following diagram shows the relationship between these resources.

Blob 存储体系结构的图示

使用以下 Python 类与这些资源进行交互:Use the following Python classes to interact with these resources:

  • BlobServiceClientBlobServiceClient 类可用于操纵 Azure 存储资源和 blob 容器。BlobServiceClient: The BlobServiceClient class allows you to manipulate Azure Storage resources and blob containers.
  • ContainerClientContainerClient 类可用于操纵 Azure 存储容器及其 blob。ContainerClient: The ContainerClient class allows you to manipulate Azure Storage containers and their blobs.
  • BlobClientBlobClient 类可用于操纵 Azure 存储 blob。BlobClient: The BlobClient class allows you to manipulate Azure Storage blobs.

代码示例Code examples

这些示例代码片段演示如何使用适用于 Python 的 Azure Blob 存储客户端库执行以下步骤:These example code snippets show you how to perform the following with the Azure Blob storage client library for Python:

获取连接字符串Get the connection string

下面的代码从配置存储连接字符串部分中创建的环境变量中检索存储帐户的连接字符串。The code below retrieves the connection string for the storage account from the environment variable created in the Configure your storage connection string section.

try 块内添加此代码:Add this code inside the try block:

# Retrieve the connection string for use with the application. The storage
# connection string is stored in an environment variable on the machine
# running the application called AZURE_STORAGE_CONNECTION_STRING. If the environment variable is
# created after the application is launched in a console or with Visual Studio,
# the shell or application needs to be closed and reloaded to take the
# environment variable into account.
connect_str = os.getenv('AZURE_STORAGE_CONNECTION_STRING')

创建容器Create a container

确定新容器的名称。Decide on a name for the new container. 以下代码将 UUID 值追加到容器名称,确保其是唯一的。The code below appends a UUID value to the container name to ensure that it is unique.

重要

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

调用 from_connection_string 方法,创建 BlobServiceClient 类的实例。Create an instance of the BlobServiceClient class by calling the from_connection_string method. 然后,调用 create_container 方法在存储帐户中实际创建容器。Then, call the create_container method to actually create the container in your storage account.

将此代码添加到 try 块的末尾:Add this code to the end of the try block:

# Create the BlobServiceClient object which will be used to create a container client
blob_service_client = BlobServiceClient.from_connection_string(connect_str)

# Create a unique name for the container
container_name = "quickstart" + str(uuid.uuid4())

# Create the container
container_client = blob_service_client.create_container(container_name)

将 blob 上传到容器中Upload blobs to a container

以下代码片段:The following code snippet:

  1. 在本地目录中创建文本文件。Creates a text file in the local directory.
  2. 通过从创建容器部分中调用 BlobServiceClient 上的 get_blob_client 方法,获取对 BlobClient 对象的引用。Gets a reference to a BlobClient object by calling the get_blob_client method on the BlobServiceClient from the Create a container section.
  3. 通过调用 upload_blob 方法将本地文本文件上传到 blob。Uploads the local text file to the blob by calling the upload_blob method.

将此代码添加到 try 块的末尾:Add this code to the end of the try block:

# Create a file in local data directory to upload and download
local_path = "./data"
local_file_name = "quickstart" + str(uuid.uuid4()) + ".txt"
upload_file_path = os.path.join(local_path, local_file_name)

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

# Create a blob client using the local file name as the name for the blob
blob_client = blob_service_client.get_blob_client(container=container_name, blob=local_file_name)

print("\nUploading to Azure Storage as blob:\n\t" + local_file_name)

# Upload the created file
with open(upload_file_path, "rb") as data:
    blob_client.upload_blob(data)

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

通过调用 list_blobs 方法,列出容器中的 blob。List the blobs in the container by calling the list_blobs method. 在这种情况下,只向容器添加了一个 blob,因此列表操作只返回那个 blob。In this case, only one blob has been added to the container, so the listing operation returns just that one blob.

将此代码添加到 try 块的末尾:Add this code to the end of the try block:

print("\nListing blobs...")

# List the blobs in the container
blob_list = container_client.list_blobs()
for blob in blob_list:
    print("\t" + blob.name)

下载 BlobDownload blobs

通过调用 download_blob 方法,下载以前创建的 blob。Download the previously created blob by calling the download_blob method. 示例代码将向文件名添加后缀“DOWNLOAD”,这样你就可以在本地文件系统中看到这两个文件。The example code adds a suffix of "DOWNLOAD" to the file name so that you can see both files in local file system.

将此代码添加到 try 块的末尾:Add this code to the end of the try block:

# Download the blob to a local file
# Add 'DOWNLOAD' before the .txt extension so you can see both files in the data directory
download_file_path = os.path.join(local_path, str.replace(local_file_name ,'.txt', 'DOWNLOAD.txt'))
print("\nDownloading blob to \n\t" + download_file_path)

with open(download_file_path, "wb") as download_file:
    download_file.write(blob_client.download_blob().readall())

删除容器Delete a container

以下代码使用 delete_container 方法删除整个容器,从而清除该应用所创建的资源。The following code cleans up the resources the app created by removing the entire container using the delete_container method. 也可根据需要删除本地文件。You can also delete the local files, if you like.

在删除 blob、容器和本地文件之前,应用会调用 input() 以暂停并等待用户输入。The app pauses for user input by calling input() before it deletes the blob, container, and local files. 可以通过此机会验证是否已正确创建资源,然后再删除这些资源。This is a good chance to verify that the resources were created correctly, before they are deleted.

将此代码添加到 try 块的末尾:Add this code to the end of the try block:

# Clean up
print("\nPress the Enter key to begin clean up")
input()

print("Deleting blob container...")
container_client.delete_container()

print("Deleting the local source and downloaded files...")
os.remove(upload_file_path)
os.remove(download_file_path)

print("Done")

运行代码Run the code

此应用在本地文件夹中创建测试文件,并将其上传到 Blob 存储。This app creates a test file in your local folder and uploads it to Blob storage. 然后,该示例会列出容器中的 blob,并使用新名称下载文件,这样便可对新旧文件进行对比。The example then lists the blobs in the container and downloads the file with a new name so that you can compare the old and new files.

导航到包含 blob-quickstart-v12.py 文件的目录,然后执行以下 python 命令来运行应用。Navigate to the directory containing the blob-quickstart-v12.py file, then execute the following python command to run the app.

python blob-quickstart-v12.py

应用的输出类似于以下示例:The output of the app is similar to the following example:

Azure Blob storage v12 - Python quickstart sample

Uploading to Azure Storage as blob:
        quickstartcf275796-2188-4057-b6fb-038352e35038.txt

Listing blobs...
        quickstartcf275796-2188-4057-b6fb-038352e35038.txt

Downloading blob to
        ./data/quickstartcf275796-2188-4057-b6fb-038352e35038DOWNLOAD.txt

Press the Enter key to begin clean up

Deleting blob container...
Deleting the local source and downloaded files...
Done

在开始清理过程之前,请在“data”文件夹中查看这两个文件。Before you begin the clean up process, check your data folder for the two files. 可以打开它们,然后就会观察到它们完全相同。You can open them and observe that they are identical.

验证文件后,按 Enter 键以删除测试文件并完成演示。After you've verified the files, press the Enter key to delete the test files and finish the demo.

后续步骤Next steps

本快速入门介绍了如何使用 Python 上传、下载和列出 blob。In this quickstart, you learned how to upload, download, and list blobs using Python.

若要查看 Blob 存储示例应用,请继续执行以下操作:To see Blob storage sample apps, continue to: