使用 Python 针对 Azure 文件进行开发Develop for Azure Files with Python

提示

尝试 Azure 存储资源管理器Try the Azure Storage Explorer

Azure 存储资源管理器是 Microsoft 免费提供的独立应用,适用于在 Windows、macOS 和 Linux 上以可视方式处理 Azure 存储数据。Azure Storage Explorer is a free, standalone app from Microsoft that enables you to work visually with Azure Storage data on Windows, macOS, and Linux.

本教程将演示使用 Python 开发应用程序或服务的基本信息,这些程序或服务可使用 Azure 文件存储文件数据。This tutorial will demonstrate the basics of using Python to develop applications or services that use Azure Files to store file data. 在本教程中,我们将创建一个简单的控制台应用程序,并演示如何通过 Python 和 Azure 文件执行基本操作:In this tutorial, we will create a simple console application and show how to perform basic actions with Python and Azure Files:

  • 创建 Azure 文件共享Create Azure file shares
  • 创建目录Create directories
  • 枚举 Azure 文件共享中的文件和目录Enumerate files and directories in an Azure file share
  • 上传、下载和删除文件Upload, download, and delete a file

备注

由于 Azure 文件可通过 SMB 进行访问,因此可编写简单的应用程序,通过标准 Python I/O 类和函数访问 Azure 文件共享。Because Azure Files may be accessed over SMB, it is possible to write simple applications that access the Azure file share using the standard Python I/O classes and functions. 本文将介绍如何编写使用 Azure 存储 Python SDK 的应用程序,该 SDK 使用 Azure 文件 REST API 与 Azure 文件通信。This article will describe how to write applications that use the Azure Storage Python SDK, which uses the Azure Files REST API to talk to Azure Files.

下载和安装适用于 Python 的 Azure 存储 SDKDownload and Install Azure Storage SDK for Python

适用于 Python 的 Azure 存储 SDK 需要使用 Python 2.7、3.3、3.4、3.5 或 3.6。The Azure Storage SDK for Python requires Python 2.7, 3.3, 3.4, 3.5, or 3.6.

通过 PyPi 安装Install via PyPi

要通过 Python 包索引 (PyPI) 安装,请键入:To install via the Python Package Index (PyPI), type:

pip install azure-storage-file

备注

如果要从适用于 Python 的 Azure 存储 SDK 版本 0.36 或更早版本升级,请在安装最新软件包之前使用 pip uninstall azure-storage 卸载旧版 SDK。If you are upgrading from the Azure Storage SDK for Python version 0.36 or earlier, uninstall the older SDK using pip uninstall azure-storage before installing the latest package.

有关备用安装方法,请访问 Github 上用于 Python 的 Azure 存储 SDKFor alternative installation methods, visit the Azure Storage SDK for Python on GitHub.

查看示例应用程序View the sample application

若要查看和运行示例应用程序,了解如何将 Python 与 Azure 文件存储配合使用,请参阅 Azure Storage:Getting Started with Azure Files in Python(Azure 存储:开始在 Python 中使用 Azure 文件存储)。To view and run a sample application that shows how to use Python with Azure Files, see Azure Storage: Getting Started with Azure Files in Python.

若要运行示例应用程序,请确保已安装 azure-storage-fileazure-storage-common 软件包。To run the sample application, make sure you have installed both the azure-storage-file and azure-storage-common packages.

设置应用程序以使用 Azure 文件Set up your application to use Azure Files

在希望在其中以编程方式访问 Azure 存储的任何 Python 源文件中,将以下代码添加到文件的顶部附近:Add the following near the top of any Python source file in which you wish to programmatically access Azure Storage.

from azure.storage.file import FileService

设置与 Azure 文件的连接Set up a connection to Azure Files

通过 FileService 对象,可使用共享、目录和文件。The FileService object lets you work with shares, directories and files. 以下代码使用存储帐户名称和帐户密钥创建一个 FileService 对象。The following code creates a FileService object using the storage account name and account key. <myaccount><mykey> 替换为自己的帐户名和密钥。Replace <myaccount> and <mykey> with your account name and key.

file_service = FileService(account_name='myaccount', account_key='mykey')

创建 Azure 文件共享Create an Azure file share

在以下代码示例中,如果共享不存在,可以使用 FileService 对象来创建它。In the following code example, you can use a FileService object to create the share if it doesn't exist.

file_service.create_share('myshare')

创建目录Create a directory

也可将文件置于子目录中,而不是将其全部置于根目录中,以便对存储进行有效的组织。You can also organize storage by putting files inside sub-directories instead of having all of them in the root directory. 使用 Azure 文件可以创建帐户允许的任意数目的目录。Azure Files allows you to create as many directories as your account will allow. 以下代码在根目录下创建名为 sampledir 的子目录。The code below will create a sub-directory named sampledir under the root directory.

file_service.create_directory('myshare', 'sampledir')

枚举 Azure 文件共享中的文件和目录Enumerate files and directories in an Azure file share

若要列出共享中的文件和目录,请使用 list_directories_and_files 方法。To list the files and directories in a share, use the list_directories_and_files method. 此方法会返回一个生成器。This method returns a generator. 以下代码将共享中每个文件和目录的名称输出到控制台。The following code outputs the name of each file and directory in a share to the console.

generator = file_service.list_directories_and_files('myshare')
for file_or_dir in generator:
    print(file_or_dir.name)

上传文件Upload a file

Azure 文件共享至少包含文件可以驻留的根目录。Azure file share contains at the very least, a root directory where files can reside. 本部分会介绍如何将文件从本地存储上传到共享所在的根目录。In this section, you'll learn how to upload a file from local storage onto the root directory of a share.

若要创建文件并上传数据,请使用 create_file_from_pathcreate_file_from_streamcreate_file_from_bytescreate_file_from_text 方法。To create a file and upload data, use the create_file_from_path, create_file_from_stream, create_file_from_bytes or create_file_from_text methods. 这些方法属于高级方法,在数据大小超过 64 MB 时执行必要的分块。They are high-level methods that perform the necessary chunking when the size of the data exceeds 64 MB.

create_file_from_path 从指定路径上传文件内容,create_file_from_stream 从已经打开的文件/流上传内容。create_file_from_path uploads the contents of a file from the specified path, and create_file_from_stream uploads the contents from an already opened file/stream. create_file_from_bytes 上传字节数组,create_file_from_text 使用指定的编码(默认为 UTF-8)上传指定的文本值。create_file_from_bytes uploads an array of bytes, and create_file_from_text uploads the specified text value using the specified encoding (defaults to UTF-8).

下面的示例将 sunset.png 文件的内容上传到 myfile 文件中。The following example uploads the contents of the sunset.png file into the myfile file.

from azure.storage.file import ContentSettings
file_service.create_file_from_path(
    'myshare',
    None,  # We want to create this blob in the root directory, so we specify None for the directory_name
    'myfile',
    'sunset.png',
    content_settings=ContentSettings(content_type='image/png'))

下载文件Download a file

若要从文件中下载数据,请使用 get_file_to_pathget_file_to_streamget_file_to_bytesget_file_to_textTo download data from a file, use get_file_to_path, get_file_to_stream, get_file_to_bytes, or get_file_to_text. 这些方法属于高级方法,在数据大小超过 64 MB 时执行必要的分块。They are high-level methods that perform the necessary chunking when the size of the data exceeds 64 MB.

以下示例演示如何使用 get_file_to_path 下载 myfile 文件的内容,并将其存储到 out-sunset.png 文件。The following example demonstrates using get_file_to_path to download the contents of the myfile file and store it to the out-sunset.png file.

file_service.get_file_to_path('myshare', None, 'myfile', 'out-sunset.png')

删除文件Delete a file

最后,若要删除文件,请调用 delete_fileFinally, to delete a file, call delete_file.

file_service.delete_file('myshare', None, 'myfile')

创建共享快照Create share snapshot

可以创建整个文件共享的时点副本。You can create a point in time copy of your entire file share.

snapshot = file_service.snapshot_share(share_name)
snapshot_id = snapshot.snapshot

使用元数据创建共享快照Create share snapshot with metadata

metadata = {"foo": "bar"}
snapshot = file_service.snapshot_share(share_name, metadata=metadata)

列出共享和快照List shares and snapshots

可以为特定的共享列出所有快照。You can list all the snapshots for a particular share.

shares = list(file_service.list_shares(include_snapshots=True))

浏览共享快照Browse share snapshot

可以浏览每个共享快照的内容来检索相应时间点的文件和目录。You can browse content of each share snapshot to retrieve files and directories from that point in time.

directories_and_files = list(
    file_service.list_directories_and_files(share_name, snapshot=snapshot_id))

从共享快照获取文件Get file from share snapshot

可以从共享快照下载用于还原方案的文件。You can download a file from a share snapshot for your restore scenario.

with open(FILE_PATH, 'wb') as stream:
    file = file_service.get_file_to_stream(
        share_name, directory_name, file_name, stream, snapshot=snapshot_id)

删除单个共享快照Delete a single share snapshot

可以删除单个共享快照。You can delete a single share snapshot.

file_service.delete_share(share_name, snapshot=snapshot_id)

共享快照存在时,删除共享Delete share when share snapshots exist

无法删除包含快照的共享,除非先删除所有快照。A share that contains snapshots cannot be deleted unless all the snapshots are deleted first.

file_service.delete_share(share_name, delete_snapshots=DeleteSnapshot.Include)

后续步骤Next steps

了解如何使用 Python 操作 Azure 文件后,请单击以下链接了解更多信息。Now that you've learned how to manipulate Azure Files with Python, follow these links to learn more.