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

了解有关如何使用 Python 开发应用或服务的基础知识,这些应用或服务会使用 Azure 文件存储来存储文件数据。Learn the basics of using Python to develop apps or services that use Azure Files to store file data. 创建一个简单的控制台应用,并了解如何使用 Python 和 Azure 文件存储执行基本操作:Create a simple console app and learn 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
  • 使用快照创建文件共享备份Create file share backups by using snapshots

备注

由于 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 apps that use the Azure Files 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 版本 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.

用于 Python 的 Azure 文件存储客户端库 v12 需要 Python 2.7 或 3.5。The Azure File Storage client library v12.x for Python requires Python 2.7 or 3.5.

通过 PyPI 安装Install via PyPI

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

pip install azure-storage-file-share

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

将以下代码添加到 Python 源文件顶部附近,以使用本文中的代码片段。Add the following near the top of a Python source file to use the code snippets in this article.

from azure.core.exceptions import (
    ResourceExistsError,
    ResourceNotFoundError
)

from azure.storage.fileshare import (
    ShareServiceClient,
    ShareClient,
    ShareDirectoryClient,
    ShareFileClient
)

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

通过 ShareServiceClient,可以使用共享、目录和文件。ShareServiceClient lets you work with shares, directories, and files. 以下代码使用存储帐户连接字符串创建 ShareServiceClient 对象。The following code creates a ShareServiceClient object using the storage account connection string.

# Create a ShareServiceClient from a connection string
service_client = ShareServiceClient.from_connection_string(connection_string)

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

以下代码示例使用 ShareClient 对象来创建共享(如果该共享不存在)。The following code example uses a ShareClient object to create the share if it doesn't exist.

def create_file_share(self, connection_string, share_name):
    try:
        # Create a ShareClient from a connection string
        share_client = ShareClient.from_connection_string(
            connection_string, share_name)

        print("Creating share:", share_name)
        share_client.create_share()

    except ResourceExistsError as ex:
        print("ResourceExistsError:", ex.message)

创建目录Create a directory

可以将文件置于子目录中,不必将其全部置于根目录中,以便对存储进行有效的组织。You can organize storage by putting files inside subdirectories instead of having all of them in the root directory.

下面的方法通过使用 ShareDirectoryClient 对象在指定文件共享的根目录中创建一个目录。The following method creates a directory in the root of the specified file share by using a ShareDirectoryClient object.

def create_directory(self, connection_string, share_name, dir_name):
    try:
        # Create a ShareDirectoryClient from a connection string
        dir_client = ShareDirectoryClient.from_connection_string(
            connection_string, share_name, dir_name)

        print("Creating directory:", share_name + "/" + dir_name)
        dir_client.create_directory()

    except ResourceExistsError as ex:
        print("ResourceExistsError:", ex.message)

上传文件Upload a file

本部分会介绍如何将文件从本地存储上传到 Azure 文件存储。In this section, you'll learn how to upload a file from local storage into Azure File Storage.

下面的方法将指定文件的内容上传到指定的 Azure 文件共享中的指定目录。The following method uploads the contents of the specified file into the specified directory in the specified Azure file share.

def upload_local_file(self, connection_string, local_file_path, share_name, dest_file_path):
    try:
        source_file = open(local_file_path, "rb")
        data = source_file.read()

        # Create a ShareFileClient from a connection string
        file_client = ShareFileClient.from_connection_string(
            connection_string, share_name, dest_file_path)

        print("Uploading to:", share_name + "/" + dest_file_path)
        file_client.upload_file(data)

    except ResourceExistsError as ex:
        print("ResourceExistsError:", ex.message)

    except ResourceNotFoundError as ex:
        print("ResourceNotFoundError:", ex.message)

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

若要列出子目录中的文件和目录,请使用 list_directories_and_files 方法。To list the files and directories in a subdirectory, use the list_directories_and_files method. 此方法返回自动分页迭代器。This method returns an auto-paging iterable. 以下代码将指定目录中每个文件和子目录的名称输出到控制台。The following code outputs the name of each file and subdirectory in the specified directory to the console.

def list_files_and_dirs(self, connection_string, share_name, dir_name):
    try:
        # Create a ShareClient from a connection string
        share_client = ShareClient.from_connection_string(
            connection_string, share_name)

        for item in list(share_client.list_directories_and_files(dir_name)):
            if item["is_directory"]:
                print("Directory:", item["name"])
            else:
                print("File:", dir_name + "/" + item["name"])

    except ResourceNotFoundError as ex:
        print("ResourceNotFoundError:", ex.message)

下载文件Download a file

若要从文件中下载数据,请使用 download_fileTo download data from a file, use download_file.

下面的示例演示如何使用 download_file 获取指定文件的内容并将其存储在本地(“DOWNLOADED-”会预置到文件名之前)。The following example demonstrates using download_file to get the contents of the specified file and store it locally with DOWNLOADED- prepended to the filename.

def download_azure_file(self, connection_string, share_name, dir_name, file_name):
    try:
        # Build the remote path
        source_file_path = dir_name + "/" + file_name

        # Add a prefix to the filename to 
        # distinguish it from the uploaded file
        dest_file_name = "DOWNLOADED-" + file_name

        # Create a ShareFileClient from a connection string
        file_client = ShareFileClient.from_connection_string(
            connection_string, share_name, source_file_path)

        print("Downloading to:", dest_file_name)

        # Open a file for writing bytes on the local system
        with open(dest_file_name, "wb") as data:
            # Download the file from Azure into a stream
            stream = file_client.download_file()
            # Write the stream to the local file
            data.write(stream.readall())

    except ResourceNotFoundError as ex:
        print("ResourceNotFoundError:", ex.message)

创建共享快照Create a share snapshot

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

def create_snapshot(self, connection_string, share_name):
    try:
        # Create a ShareClient from a connection string
        share_client = ShareClient.from_connection_string(
            connection_string, share_name)

        # Create a snapshot
        snapshot = share_client.create_snapshot()
        print("Created snapshot:", snapshot["snapshot"])

        # Return the snapshot time so 
        # it can be accessed later
        return snapshot["snapshot"]

    except ResourceNotFoundError as ex:
        print("ResourceNotFoundError:", ex.message)

列出共享和快照List shares and snapshots

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

def list_shares_snapshots(self, connection_string):
    try:
        # Create a ShareServiceClient from a connection string
        service_client = ShareServiceClient.from_connection_string(connection_string)

        # List the shares in the file service
        shares = list(service_client.list_shares(include_snapshots=True))

        for share in shares:
            if (share["snapshot"]):
                print("Share:", share["name"], "Snapshot:", share["snapshot"])
            else:
                print("Share:", share["name"])

    except ResourceNotFoundError as ex:
        print("ResourceNotFoundError:", ex.message)

浏览共享快照Browse share snapshot

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

def browse_snapshot_dir(self, connection_string, share_name, snapshot_time, dir_name):
    try:
        # Create a ShareClient from a connection string
        snapshot = ShareClient.from_connection_string(
            conn_str=connection_string, share_name=share_name, snapshot=snapshot_time)

        print("Snapshot:", snapshot_time)

        for item in list(snapshot.list_directories_and_files(dir_name)):
            if item["is_directory"]:
                print("Directory:", item["name"])
            else:
                print("File:", dir_name + "/" + item["name"])

    except ResourceNotFoundError as ex:
        print("ResourceNotFoundError:", ex.message)

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

可以从共享快照下载文件。You can download a file from a share snapshot. 这使你可以还原文件的早期版本。This enables you to restore a previous version of a file.

def download_snapshot_file(self, connection_string, share_name, snapshot_time, dir_name, file_name):
    try:
        # Build the remote path
        source_file_path = dir_name + "/" + file_name

        # Add a prefix to the local filename to 
        # indicate it's a file from a snapshot
        dest_file_name = "SNAPSHOT-" + file_name

        # Create a ShareFileClient from a connection string
        snapshot_file_client = ShareFileClient.from_connection_string(
            conn_str=connection_string, share_name=share_name, 
            file_path=source_file_path, snapshot=snapshot_time)

        print("Downloading to:", dest_file_name)

        # Open a file for writing bytes on the local system
        with open(dest_file_name, "wb") as data:
            # Download the file from Azure into a stream
            stream = snapshot_file_client.download_file()
            # Write the stream to the local file
            data.write(stream.readall())

    except ResourceNotFoundError as ex:
        print("ResourceNotFoundError:", ex.message)

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

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

def delete_snapshot(self, connection_string, share_name, snapshot_time):
    try:
        # Create a ShareClient for a snapshot
        snapshot_client = ShareClient.from_connection_string(conn_str=connection_string, share_name=share_name, snapshot=snapshot_time)

        print("Deleting snapshot:", snapshot_time)

        # Delete the snapshot
        snapshot_client.delete_share()

    except ResourceNotFoundError as ex:
        print("ResourceNotFoundError:", ex.message)

删除文件Delete a file

若要删除文件,请调用 delete_fileTo delete a file, call delete_file.

def delete_azure_file(self, connection_string, share_name, file_path):
    try:
        # Create a ShareFileClient from a connection string
        file_client = ShareFileClient.from_connection_string(
            connection_string, share_name, file_path)

        print("Deleting file:", share_name + "/" + file_path)

        # Delete the file
        file_client.delete_file()

    except ResourceNotFoundError as ex:
        print("ResourceNotFoundError:", ex.message)

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

若要删除包含快照的共享,请调用带有 delete_snapshots=Truedelete_shareTo delete a share that contains snapshots, call delete_share with delete_snapshots=True.

def delete_share(self, connection_string, share_name):
    try:
        # Create a ShareClient from a connection string
        share_client = ShareClient.from_connection_string(
            connection_string, share_name)

        print("Deleting share:", share_name)

        # Delete the share and snapshots
        share_client.delete_share(delete_snapshots=True)

    except ResourceNotFoundError as ex:
        print("ResourceNotFoundError:", ex.message)

后续步骤Next steps

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