你当前正在访问 Microsoft Azure Global Edition 技术文档网站。 如果需要访问由世纪互联运营的 Microsoft Azure 中国技术文档网站,请访问 https://docs.azure.cn

适用于 Python 的 Azure 存储文件共享客户端库 - 版本 12.15.0

Azure 文件共享存储在云中提供完全托管的文件共享,可通过行业标准 的服务器消息块 (SMB) 协议进行访问。 Azure 文件共享可由云或者 Windows、Linux 和 macOS 的本地部署同时装载。 此外,可以使用 Azure 文件同步将 Azure 文件共享缓存在 Windows Server 上,以加快访问速度(与在数据使用位置进行访问的速度相当)。

Azure 文件共享可用于:

  • 取代或补充本地文件服务器
  • “直接迁移”应用程序
  • 使用共享应用程序设置、诊断共享和开发/测试/调试工具简化云开发

源代码 | 包 (PyPI) | 包 (Conda) | API 参考文档 | 产品文档 | 样品

入门

先决条件

安装包

使用 pip 安装适用于 Python 的 Azure 存储文件共享客户端库:

pip install azure-storage-file-share

创建存储帐户

如果要创建新的存储帐户,可以使用 Azure 门户Azure PowerShellAzure CLI

# Create a new resource group to hold the storage account -
# if using an existing resource group, skip this step
az group create --name my-resource-group --location westus2

# Create the storage account
az storage account create -n my-storage-account-name -g my-resource-group

创建客户端

使用适用于 Python 的 Azure 存储文件共享客户端库,可以与四种类型的资源进行交互:存储帐户本身、文件共享、目录和文件。 与这些资源的交互从 客户端的实例开始。 若要创建客户端对象,需要存储帐户的文件服务 URL 和可用于访问存储帐户的凭据:

from azure.storage.fileshare import ShareServiceClient

service = ShareServiceClient(account_url="https://<my-storage-account-name>.file.core.windows.net/", credential=credential)

查找帐户 URL

可以使用 Azure 门户Azure PowerShellAzure CLI 查找存储帐户的文件服务 URL:

# Get the file service URL for the storage account
az storage account show -n my-storage-account-name -g my-resource-group --query "primaryEndpoints.file"

凭据类型

参数 credential 可能以多种不同的形式提供,具体取决于要使用的 授权 类型:

  1. 若要使用 共享访问签名 (SAS) 令牌,请以字符串的形式提供令牌。 如果帐户 URL 包含 SAS 令牌,请省略凭据参数。 可以从 Azure 门户的“共享访问签名”下生成 SAS 令牌,或使用以下 generate_sas() 函数之一为存储帐户、共享或文件创建 sas 令牌:

    from datetime import datetime, timedelta
    from azure.storage.fileshare import ShareServiceClient, generate_account_sas, ResourceTypes, AccountSasPermissions
    
    sas_token = generate_account_sas(
        account_name="<storage-account-name>",
        account_key="<account-access-key>",
        resource_types=ResourceTypes(service=True),
        permission=AccountSasPermissions(read=True),
        expiry=datetime.utcnow() + timedelta(hours=1)
    )
    
    share_service_client = ShareServiceClient(account_url="https://<my_account_name>.file.core.windows.net", credential=sas_token)
    
  2. 若要使用存储帐户 共享密钥 (又名帐户密钥或访问密钥) ,请以字符串的形式提供密钥。 这可以在 Azure 门户的“访问密钥”部分下找到,也可以通过运行以下 Azure CLI 命令找到:

    az storage account keys list -g MyResourceGroup -n MyStorageAccount

    使用密钥作为凭据参数对客户端进行身份验证:

    from azure.storage.fileshare import ShareServiceClient
    service = ShareServiceClient(account_url="https://<my_account_name>.file.core.windows.net", credential="<account_access_key>")
    

从连接字符串创建客户端

根据用例和授权方法,你可能更喜欢使用存储连接字符串初始化客户端实例,而不是单独提供帐户 URL 和凭据。 为此,请将存储连接字符串传递给客户端的 from_connection_string 类方法:

from azure.storage.fileshare import ShareServiceClient

connection_string = "DefaultEndpointsProtocol=https;AccountName=xxxx;AccountKey=xxxx;EndpointSuffix=core.windows.net"
service = ShareServiceClient.from_connection_string(conn_str=connection_string)

存储帐户的连接字符串可以在 Azure 门户的“访问密钥”部分下找到,也可以通过运行以下 CLI 命令找到:

az storage account show-connection-string -g MyResourceGroup -n MyStorageAccount

关键概念

以下组件构成 Azure 文件共享服务:

  • 存储帐户本身
  • 存储帐户中的文件共享
  • 文件共享中目录的可选层次结构
  • 文件共享中的文件,最大大小可能为 1 TiB

使用适用于 Python 的 Azure 存储文件共享客户端库,可以使用专用客户端对象来与其中每个组件进行交互。

异步客户端

此库包含 Python 3.5+ 上支持的完整异步 API。 若要使用它,必须先安装异步传输,例如 aiohttp。 有关详细信息,请参阅 azure-core 文档

不再需要异步客户端和凭据时,应将其关闭。 这些对象是异步上下文管理器并定义异步 close 方法。

客户端

提供了四个不同的客户端来与文件共享服务的各个组件进行交互:

  1. ShareServiceClient - 此客户端表示与 Azure 存储帐户本身的交互,并允许你获取预配置的客户端实例以访问其中的文件共享。 它提供检索和配置服务属性以及列出、创建和删除帐户中的共享的操作。 若要对特定共享执行操作,请使用 get_share_client 方法检索客户端。
  2. ShareClient - 此客户端表示与特定文件共享 () 的交互,并允许你获取预配置的客户端实例以访问其中的目录和文件。 它提供创建、删除、配置或创建共享快照的操作,并包括创建和枚举其中目录内容的操作。 若要对特定目录或文件执行操作,请使用 get_directory_clientget_file_client 方法检索客户端。
  3. ShareDirectoryClient - 此客户端表示与特定目录 () 尚不存在的交互。 它提供创建、删除或枚举即时或嵌套子目录的内容的操作,并包括在其中创建和删除文件的操作。 对于与特定子目录或文件相关的操作,也可以使用 和 get_file_client 函数检索get_subdirectory_client该实体的客户端。
  4. ShareFileClient - 此客户端表示与特定文件 (交互) 尚不存在。 它提供上传、下载、创建、删除和复制文件的操作。

有关路径命名限制的详细信息,请参阅 命名和引用共享、目录、文件和元数据

示例

以下部分提供了几个代码片段,涵盖了一些最常见的存储文件共享任务,包括:

创建文件共享

创建文件共享以存储文件

from azure.storage.fileshare import ShareClient

share = ShareClient.from_connection_string(conn_str="<connection_string>", share_name="myshare")
share.create_share()

使用异步客户端创建文件共享

from azure.storage.fileshare.aio import ShareClient

share = ShareClient.from_connection_string(conn_str="<connection_string>", share_name="myshare")
await share.create_share()

上传文件

将文件上传到共享

from azure.storage.fileshare import ShareFileClient

file_client = ShareFileClient.from_connection_string(conn_str="<connection_string>", share_name="myshare", file_path="my_file")

with open("./SampleSource.txt", "rb") as source_file:
    file_client.upload_file(source_file)

异步上传文件

from azure.storage.fileshare.aio import ShareFileClient

file_client = ShareFileClient.from_connection_string(conn_str="<connection_string>", share_name="myshare", file_path="my_file")

with open("./SampleSource.txt", "rb") as source_file:
    await file_client.upload_file(source_file)

下载文件

从共享下载文件

from azure.storage.fileshare import ShareFileClient

file_client = ShareFileClient.from_connection_string(conn_str="<connection_string>", share_name="myshare", file_path="my_file")

with open("DEST_FILE", "wb") as file_handle:
    data = file_client.download_file()
    data.readinto(file_handle)

异步下载文件

from azure.storage.fileshare.aio import ShareFileClient

file_client = ShareFileClient.from_connection_string(conn_str="<connection_string>", share_name="myshare", file_path="my_file")

with open("DEST_FILE", "wb") as file_handle:
    data = await file_client.download_file()
    await data.readinto(file_handle)

列出目录的内容

列出父目录下的所有目录和文件

from azure.storage.fileshare import ShareDirectoryClient

parent_dir = ShareDirectoryClient.from_connection_string(conn_str="<connection_string>", share_name="myshare", directory_path="parent_dir")

my_list = list(parent_dir.list_directories_and_files())
print(my_list)

异步列出目录的内容

from azure.storage.fileshare.aio import ShareDirectoryClient

parent_dir = ShareDirectoryClient.from_connection_string(conn_str="<connection_string>", share_name="myshare", directory_path="parent_dir")

my_files = []
async for item in parent_dir.list_directories_and_files():
    my_files.append(item)
print(my_files)

可选配置

可选关键字 (keyword) 可在客户端和每个操作级别传入的参数。

重试策略配置

在实例化客户端时使用以下关键字 (keyword) 参数来配置重试策略:

  • retry_total (int) :允许的重试总数。 优先于其他计数。 retry_total=0如果不想对请求重试,请传入 。 默认值为 10。
  • retry_connect (int) :重试多少个与连接相关的错误。 默认值为 3。
  • retry_read (int) :读取错误时重试的次数。 默认值为 3。
  • retry_status (int) :对错误状态代码重试的次数。 默认值为 3。
  • retry_to_secondary (bool) :是否应将请求重试到辅助数据库(如果可以)。 应仅启用 RA-GRS 帐户,并可以处理可能过时的数据。 默认为 False

其他客户端/按操作配置

其他可选配置关键字 (keyword) 可在客户端或按操作指定的参数。

客户端关键字 (keyword) 参数:

  • connection_timeout (int) :客户端将等待与服务器建立连接的秒数。 默认为 20 秒。
  • read_timeout (int) :客户端在连续读取操作之间等待服务器响应的秒数。 这是套接字级超时,不受整体数据大小的影响。 将自动重试客户端读取超时。 默认值为 60 秒。
  • 传输 (任何) :用户提供的用于发送 HTTP 请求的传输。

按操作关键字 (keyword) 参数:

  • raw_response_hook (可调用) :给定回调使用从服务返回的响应。
  • raw_request_hook (可调用) :给定的回调在发送到服务之前使用请求。
  • client_request_id (str) :请求的可选用户指定标识。
  • user_agent (str) :将自定义值追加到要随请求一起发送的用户代理标头。
  • logging_enable (bool) :在 DEBUG 级别启用日志记录。 默认为 False。 也可以在客户端级别传入,以为所有请求启用它。
  • logging_body (bool) :启用记录请求和响应正文。 默认为 False。 也可以在客户端级别传入,以为所有请求启用它。
  • 标头 (dict) :将自定义标头作为键值对传入。 例如 headers={'CustomValue': value}

疑难解答

常规

存储文件客户端会引发 Azure Core 中定义的异常。

此列表可用于引用以捕获引发的异常。 若要获取异常的特定错误代码,请使用 error_code 属性,即 exception.error_code

日志记录

此库使用标准 日志记录 库进行日志记录。 有关 HTTP 会话 (URL、标头等的基本信息,) 在 INFO 级别记录。

可以使用 参数在客户端 logging_enable 上启用详细的调试级别日志记录,包括请求/响应正文和未处理标头:

import sys
import logging
from azure.storage.fileshare import ShareServiceClient

# Create a logger for the 'azure.storage.fileshare' SDK
logger = logging.getLogger('azure.storage.fileshare')
logger.setLevel(logging.DEBUG)

# Configure a console output
handler = logging.StreamHandler(stream=sys.stdout)
logger.addHandler(handler)

# This client will log detailed information about its HTTP sessions, at DEBUG level
service_client = ShareServiceClient.from_connection_string("your_connection_string", logging_enable=True)

同样,即使没有为客户端启用详细日志记录,logging_enable 也可以为单个操作启用:

service_client.get_service_properties(logging_enable=True)

后续步骤

更多示例代码

开始使用文件共享 示例

SDK 的 GitHub 存储库中提供了多个存储文件共享 Python SDK 示例。 这些示例提供了使用存储文件共享时经常遇到的其他方案的示例代码:

其他文档

有关 Azure 文件共享存储的更广泛文档,请参阅有关 docs.microsoft.com 的 Azure 文件共享存储文档

贡献

本项目欢迎贡献和建议。 大多数贡献要求你同意贡献者许可协议 (CLA),并声明你有权(并且确实有权)授予我们使用你的贡献的权利。 有关详细信息,请访问 https://cla.microsoft.com

提交拉取请求时,CLA 机器人将自动确定你是否需要提供 CLA,并相应地修饰 PR(例如标签、注释)。 直接按机器人提供的说明操作。 只需使用 CLA 对所有存储库执行一次这样的操作。

此项目采用了 Microsoft 开放源代码行为准则。 有关详细信息,请参阅行为准则常见问题解答,或如果有任何其他问题或意见,请与 联系。