了解如何开发使用 Azure 文件存储数据的 Python 应用程序。 Azure 文件是云中的托管文件共享服务。 它提供可通过行业标准服务器消息块(SMB)和网络文件系统(NFS)协议访问的完全托管文件共享。 Azure 文件存储还提供 REST API,用于以编程方式访问文件共享。
在本文中,你将了解使用 Python 中的 Azure 文件开发的不同方法,以及如何选择最适合应用需求的方法。 你还将了解如何创建与 Azure 文件资源交互的基本控制台应用。
适用于
管理模型 | 计费模式 | 媒体层 | 冗余 | 中小型企业 (SMB) | 网络文件系统(NFS) |
---|---|---|---|---|---|
Microsoft.Storage | 预配 v2 | HDD(标准) | 本地 (LRS) | ![]() |
![]() |
Microsoft.Storage | 预配 v2 | HDD(标准) | 区域 (ZRS) | ![]() |
![]() |
Microsoft.Storage | 预配 v2 | HDD(标准) | 异地 (GRS) | ![]() |
![]() |
Microsoft.Storage | 预配 v2 | HDD(标准) | GeoZone (GZRS) | ![]() |
![]() |
Microsoft.Storage | 预配版本 v1 | SSD(高级) | 本地 (LRS) | ![]() |
![]() |
Microsoft.Storage | 预配版本 v1 | SSD(高级) | 区域 (ZRS) | ![]() |
![]() |
Microsoft.Storage | 即用即付 | HDD(标准) | 本地 (LRS) | ![]() |
![]() |
Microsoft.Storage | 即用即付 | HDD(标准) | 区域 (ZRS) | ![]() |
![]() |
Microsoft.Storage | 即用即付 | HDD(标准) | 异地 (GRS) | ![]() |
![]() |
Microsoft.Storage | 即用即付 | HDD(标准) | GeoZone (GZRS) | ![]() |
![]() |
关于使用 Azure 文件的 Python 应用开发
Azure 文件存储为 Python 开发人员提供了多种方式来访问数据和管理 Azure 文件存储中的资源。 下表列出了这些方法,总结了它们的工作方式,并提供有关何时使用每个方法的指导:
方法 | 工作原理 | 何时使用 |
---|---|---|
标准文件 I/O 库 | 通过使用 SMB 或 NFS 装载的 Azure 文件共享使用 OS 级 API 调用。 在使用 SMB/NFS 挂载文件共享时,可以使用编程语言或框架(如 Python)的文件 I/O 库,例如 os 和 io 。 |
你拥有已有代码使用标准文件 I/O 的业务线应用,并且不希望重写代码来让应用程序可以与 Azure 文件共享一起使用。 |
FileREST API | 直接调用 HTTPS 终结点以与存储在 Azure 文件中的数据进行交互。 提供对文件共享资源的编程控制。 Azure SDK 提供基于 FileREST API 构建的文件共享客户端库(azure-storage-file-share ),允许你通过熟悉的 Python 编程语言范例与 FileREST API作进行交互。 |
你要为客户生成增值云服务和应用,并且想要使用无法通过 Python 文件 I/O 库提供的高级功能。 |
存储资源提供程序 REST API | 使用 Azure 资源管理器(ARM)管理存储帐户和文件共享。 为了进行各种资源管理操作,调用REST API终结点。 | 应用或服务需要执行资源管理任务,例如创建、删除或更新存储帐户或文件共享。 |
有关这些方法的一般信息,请参阅 Azure 文件存储的应用程序开发概述。
本文重点介绍如何使用以下方法使用 Azure 文件资源:
- 使用 Python 文件 I/O 库处理 Azure 文件:使用 SMB 或 NFS 装载文件共享,并使用 Python 文件 I/O 库处理共享中的文件和目录。
- 使用适用于 Python 的文件共享客户端库处理 Azure 文件:使用适用于 Python 的 Azure 存储文件共享客户端库处理文件共享中的文件和目录。 此客户端库基于 FileREST API 生成。
- 使用 Azure 存储管理库管理 Azure 文件资源:使用 Azure 存储管理库管理存储帐户中的文件共享和其他资源。 管理库基于 Azure 存储资源提供程序 REST API 生成。
先决条件
- Azure 订阅 - 创建免费帐户
- Azure 存储帐户 - 创建存储帐户
- Python 3.8+
设置项目
本部分将指导你准备项目以使用 Azure 文件存储。
在项目目录中,使用 pip install
命令根据应用的需求安装包。 以下示例演示如何安装 Azure 文件共享客户端库、存储管理客户端库和 Azure 标识库。 与 Azure 服务的无密码连接需要 azure-identity 包。
pip install azure-identity
pip install azure-storage-file-share
pip install azure-mgmt-resource
pip install azure-mgmt-storage
打开代码文件并添加必要的 import 语句。
如果计划使用 Python os
和 io
库,请将以下内容添加到 .py 文件中:
import os
import io
如果计划使用 Azure 存储文件共享客户端库,请将以下内容添加到 .py 文件:
from azure.identity import DefaultAzureCredential
from azure.storage.fileshare import ShareClient, ShareDirectoryClient, ShareFileClient
如果计划使用 Azure 存储管理库,请将以下内容添加到 .py 文件:
from azure.identity import DefaultAzureCredential
from azure.mgmt.resource import ResourceManagementClient
from azure.mgmt.storage import StorageManagementClient
使用 Python 文件 I/O 库处理 Azure 文件
标准文件 I/O 库是访问和使用 Azure 文件资源的最常用方法。 使用 SMB 或 NFS 装载文件共享时,操作系统会重定向本地文件系统的 API 请求。 此方法允许你使用标准文件 I/O 库(例如 os
,或 io
)与共享中的文件和目录进行交互。
当你的应用需要时,请考虑使用 Python 文件 I/O 库:
- 应用兼容性:非常适合具有已经使用 Python 文件 I/O 库的现有代码的业务线应用。 无需为应用重写代码才能使用 Azure 文件共享。
- 易于使用: Python 文件 I/O 库由开发人员熟知,易于使用。 Azure 文件存储的关键价值主张是通过 SMB 和 NFS 公开本机文件系统 API。
本部分介绍如何使用 Python 文件 I/O 库来处理 Azure 文件资源。
有关详细信息和示例,请参阅以下资源:
装载文件共享
若要使用 Python 文件 I/O 库,必须先装载文件共享。 有关如何使用 SMB 或 NFS 装载文件共享的指导,请参阅以下资源:
在本文中,我们将使用以下路径来引用 Windows 上装载的 SMB 文件共享:
file_share_path = "Z:\\file-share"
示例:使用 Python 文件 I/O 库连接到文件共享并枚举目录
下面的代码示例演示如何连接到文件共享并列出共享中的目录:
import os
def enumerate_directories(path):
try:
# Get all directories in the specified path
dirs = [d for d in os.listdir(path) if os.path.isdir(os.path.join(path, d))]
# Print each directory name
for dir_name in dirs:
print(f"{dir_name}")
print(f"{len(dirs)} directories found.")
except (PermissionError, FileNotFoundError, OSError) as ex:
print(f"Error: {ex}")
#Example usage
file_share_path = "Z:\\file-share"
enumerate_directories(file_share_path)
示例:使用 Python 文件 I/O 库写入文件共享中的文件
下面的代码示例演示如何将文本写入文件并将其追加到文件中:
import os
def write_to_file(file_share_path, file_name):
# First line of text with platform-appropriate line ending
text_to_write = "First line" + os.linesep
# Combine the file share path and filename
file_path = os.path.join(file_share_path, file_name)
# Write initial text to file (overwrites if file exists)
with open(file_path, 'w') as file:
file.write(text_to_write)
# Text to append
text_to_append = ["Second line", "Third line"]
# Append lines to the file
with open(file_path, 'a') as file:
file.write(os.linesep.join(text_to_append) + os.linesep)
# Example usage
file_share_path = "Z:\\file-share"
write_to_file(file_share_path, "test.txt")
示例:使用 Python 文件 I/O 库枚举文件 ACL
下面的代码示例演示如何枚举文件的基本访问控制列表(ACL):
import os
import stat
def enumerate_file_acls(file_path):
try:
# Get file stats
file_stat = os.stat(file_path)
# Get permissions in octal format
permissions_octal = oct(stat.S_IMODE(file_stat.st_mode))
print(f"File: {file_path}")
print(f"Permissions (octal): {permissions_octal}")
# Interpret permissions in a human-readable format
permissions = ""
permissions += "r" if file_stat.st_mode & stat.S_IRUSR else "-"
permissions += "w" if file_stat.st_mode & stat.S_IWUSR else "-"
permissions += "x" if file_stat.st_mode & stat.S_IXUSR else "-"
permissions += "r" if file_stat.st_mode & stat.S_IRGRP else "-"
permissions += "w" if file_stat.st_mode & stat.S_IWGRP else "-"
permissions += "x" if file_stat.st_mode & stat.S_IXGRP else "-"
permissions += "r" if file_stat.st_mode & stat.S_IROTH else "-"
permissions += "w" if file_stat.st_mode & stat.S_IWOTH else "-"
permissions += "x" if file_stat.st_mode & stat.S_IXOTH else "-"
print(f"Permissions (symbolic): {permissions}")
print(f"Owner ID: {file_stat.st_uid}")
print(f"Group ID: {file_stat.st_gid}")
print("Note: For detailed Windows ACLs, you may need a specialized library.")
except FileNotFoundError:
print(f"Error: File '{file_path}' not found.")
except PermissionError:
print(f"Error: Permission denied for '{file_path}'.")
except Exception as e:
print(f"Error: {e}")
# Example usage
file_share_path = "Z:\\file-share"
file_name = "test.txt"
file_path = os.path.join(file_share_path, file_name)
enumerate_file_acls(file_path)
使用适用于 Python 的文件共享客户端库处理 Azure 文件存储数据
FileREST API 提供对 Azure 文件的编程访问。 它允许调用 HTTPS 端点来对文件共享、目录和文件执行操作。 FileREST API 旨在实现高可伸缩性和高级功能,这些功能可能无法通过本机协议使用。 Azure SDK 提供基于 FileREST API 构建的客户端库,例如适用于 Python 的文件共享客户端库。
如果应用程序需要,请考虑使用 FileREST API 和文件共享客户端库:
- 高级功能: 访问无法通过原生协议获得的操作和功能。
- 自定义云集成: 生成与 Azure 文件直接交互的自定义增值服务,例如备份、防病毒或数据管理。
- 性能优化: 在大规模场景中,通过数据平面操作享受性能优势。
FileREST API 将 Azure 文件建模为资源层次结构,建议用于在 目录 或 文件 级别执行的作。 对于在文件服务或文件共享级别执行的作,应首选存储资源提供程序 REST API。
本部分介绍如何使用文件共享客户端库处理 Azure 文件资源。
有关详细信息和示例,请参阅以下资源:
授予访问权限并创建客户端
若要将应用连接到 Azure 文件存储,请创建一个 ShareClient
对象。 此对象是开始与 Azure 文件资源进行工作的起点。 以下代码示例演示如何使用不同的授权机制创建 ShareClient
对象。
若要使用 Microsoft Entra ID 进行授权,需要使用安全主体。 你需要的安全主体的类型取决于你的应用在哪里运行。 使用此表作为指南。
应用的运行位置 | 安全主体 | 指南 |
---|---|---|
本地计算机(开发和测试) | 服务主体 | 若要了解如何注册应用、设置 Microsoft Entra 组、分配角色和配置环境变量,请参阅使用开发人员服务主体授权访问 |
本地计算机(开发和测试) | 用户标识 | 若要了解如何设置 Microsoft Entra 组、分配角色和登录到 Azure,请参阅使用开发人员凭据授权访问 |
在 Azure 中托管 | 托管标识 | 若要了解如何启用托管标识和分配角色,请参阅使用托管标识授权从 Azure 托管应用访问 |
托管在 Azure 外部(例如本地应用) | 服务主体 | 若要了解如何注册应用、分配角色和配置环境变量,请参阅使用应用程序服务主体授权从本地应用访问 |
若要使用本文中的代码示例,请将 Azure RBAC 内置角色 存储文件数据特权参与者 分配给安全主体。 此角色对所有已配置存储帐户的共享中的所有数据具有完全读取、写入、修改 ACL、删除访问权限,而不考虑设置的文件/目录级别 NTFS 权限。 有关详细信息,请参阅 通过 REST 通过 Azure 文件 OAuth 使用 Microsoft Entra ID 访问 Azure 文件共享。
使用 DefaultAzureCredential 授权访问
授权访问和连接到 Azure 文件的简单安全方法是通过创建 DefaultAzureCredential 实例来获取 OAuth 令牌。 然后,你可以使用该凭据创建 ShareClient
对象。
以下示例创建一个 ShareClient
使用 DefaultAzureCredential
授权的对象,然后创建一个 ShareDirectoryClient
对象来处理共享中的目录:
from azure.identity import DefaultAzureCredential
from azure.storage.fileshare import ShareClient
account_name = "<account-name>"
share_name = "<share-name>"
# Create the share client using DefaultAzureCredential
share_client = ShareClient(
account_url=f"https://{account_name}.file.core.windows.net",
share_name=share_name,
credential=DefaultAzureCredential(),
# When using a token credential, you MUST specify a token_intent
token_intent='backup'
)
# Get a reference to a directory in the share
directory_client = share_client.get_directory_client("sample-directory")
如果确切地知道用于对用户进行身份验证的凭据类型,可以使用 用于 Python 的 Azure 标识客户端库中的其他类来获取 OAuth 令牌。 这些类派生自 TokenCredential 类。
若要详细了解每种授权机制,请参阅 “选择如何授权访问文件数据”。
示例:使用文件共享客户端库复制文件
可以使用以下方法在文件共享内或文件共享之间复制文件:
可使用 BlobClient
对象中的以下方法将文件复制到目标 Blob:
下面的代码示例演示如何将文件复制到另一个文件共享中的文件:
from azure.identity import DefaultAzureCredential
from azure.storage.fileshare import ShareFileClient
# Define storage account parameters
account_name = "<account-name>"
src_share_name = "src-file-share"
dest_share_name = "dest-file-share"
src_file_path = "src/path/to/file"
dest_file_path = "dest/path/to/file"
# Create token credential
token_credential = DefaultAzureCredential()
# Create source file client
src_file_client = ShareFileClient(
account_url=f"https://{account_name}.file.core.windows.net",
share_name=src_share_name,
file_path=src_file_path,
credential=token_credential,
token_intent='backup'
)
# Create destination file client
dest_file_client = ShareFileClient(
account_url=f"https://{account_name}.file.core.windows.net",
share_name=dest_share_name,
file_path=dest_file_path,
credential=token_credential,
token_intent='backup'
)
# Copy the file from the source share to the destination share
copy_operation = dest_file_client.start_copy_from_url(src_file_client.url)
示例:使用文件共享客户端库租用文件
租约通过租约 ID 在 Azure 管理的文件上创建锁。 租约提供了一种机制,用于协调对分布式系统中多个客户端的文件的访问。 文件的租约提供独占写入和删除访问权限。 若要详细了解租约状态和作,请参阅 租约文件。
下面的代码示例演示如何创建租约客户端、获取文件的无限持续时间租约以及释放租约:
from azure.identity import DefaultAzureCredential
from azure.storage.fileshare import ShareFileClient, ShareLeaseClient
# Define storage account parameters
account_name = "<account-name>"
share_name = "sample-file-share"
file_path = "path/to/file"
# Create a DefaultAzureCredential for authentication
token_credential = DefaultAzureCredential()
# Create a ShareFileClient
file_client = ShareFileClient(
account_url=f"https://{account_name}.file.core.windows.net",
share_name=share_name,
file_path=file_path,
credential=token_credential,
token_intent='backup'
)
# Get a lease client for the file
lease_client = ShareLeaseClient(file_client)
# Acquire an infinite duration lease on the file
lease_info = lease_client.acquire()
# Do something with the file while it's leased
# ...
# Release the lease
lease_client.release()
同时使用 SMB 和 FileREST API 时,请记住,FileREST API 使用 租约 来管理文件锁,而 SMB 使用由作系统管理的文件系统锁。 若要详细了解如何管理 SMB 与 FileREST API 之间的文件锁定交互,请参阅 管理文件锁。
示例:使用文件共享客户端库创建和列出共享快照
共享快照是某个时间点文件共享的只读副本。 可以创建文件共享的快照,然后在创建快照时使用快照访问共享中的数据。 还可以列出文件共享中的所有快照,并删除共享快照。
下面的代码示例演示如何创建共享快照、列出文件共享中的快照,以及遍历共享快照中的根目录:
from azure.storage.fileshare import ShareServiceClient, ShareDirectoryClient
def list_root_directory_snapshot(root_dir: ShareDirectoryClient):
for item in root_dir.list_directories_and_files():
if item["is_directory"]:
print(f"Directory in snapshot: {item['name']}")
else:
print(f"File in snapshot: {item['name']}")
# Connection string with account key (required for share snapshots)
connection_string = "<connection-string>"
# Create service and share clients
share_service_client = ShareServiceClient.from_connection_string(connection_string)
share_name = "sample-file-share"
share_client = share_service_client.get_share_client(share_name)
# Create a snapshot
snapshot_info = share_client.create_snapshot()
print(f"Snapshot created: {snapshot_info['snapshot']}")
# List snapshots in a share
for share_item in share_service_client.list_shares(include_snapshots=True):
if share_item["snapshot"]:
print(f"Share: {share_item['name']} (Snapshot: {share_item['snapshot']})")
# List directories and files in a share snapshot
snapshot_timestamp = snapshot_info["snapshot"]
share_snapshot = share_service_client.get_share_client(share_name, snapshot=snapshot_timestamp)
root_dir = share_snapshot.get_directory_client("")
list_root_directory_snapshot(root_dir)
注释
不允许在文件共享级别的数据平面操作中使用 OAuth 令牌,例如那些在使用 DefaultAzureCredential
时获取的令牌。 若要使用共享快照,必须使用帐户密钥对客户端对象进行授权。 ShareClient
在此代码示例中创建的对象使用连接字符串,其中包括帐户密钥。
存储帐户密钥或连接字符串会带来安全风险。 仅当Microsoft Entra 身份验证不可用时,才应使用它们。 若要详细了解如何在 Azure Key Vault 中安全地存储帐户密钥,请参阅 关于 Azure Key Vault 托管存储帐户密钥。
使用 Azure 存储管理库管理 Azure 文件资源
Azure 存储管理库基于 Azure 存储资源提供程序 REST API 构建。 Azure 存储资源提供程序是基于 Azure 资源管理器的服务,支持声明性(模板)和命令性(直接 API 调用)方法。 Azure 存储资源提供程序 REST API 提供对 Azure 存储资源的编程访问,包括文件共享。 Azure SDK 提供基于 Azure 存储资源提供程序 REST API 构建的管理库。
对于在 文件服务 或 文件共享 级别执行的作,建议使用管理库。 本部分介绍如何使用 Azure 存储管理库管理 Azure 文件资源。
示例:使用 Azure 存储管理库创建文件共享
以下代码示例演示如何创建顶级 ArmClient
对象、向订阅注册存储资源提供程序,以及如何使用 Azure 存储管理库创建文件共享:
from azure.identity import DefaultAzureCredential
from azure.mgmt.resource import ResourceManagementClient, SubscriptionClient
from azure.mgmt.storage import StorageManagementClient
from azure.mgmt.storage.models import FileShare
# Create the credential for authentication
credential = DefaultAzureCredential()
# Define variables
subscription_id = "<subscription-id>"
resource_group_name = "<resource-group-name>"
storage_account_name = "<storage-account-name>"
share_name = "sample-file-share"
# Create clients
resource_client = ResourceManagementClient(credential, subscription_id)
subscription_client = SubscriptionClient(credential)
storage_client = StorageManagementClient(credential, subscription_id)
# Register Microsoft.Storage resource provider, if not already registered
provider = resource_client.providers.get('Microsoft.Storage')
if provider.registration_state == "NotRegistered":
resource_client.providers.register('Microsoft.Storage')
# Create a file share
file_share = storage_client.file_shares.create(
resource_group_name=resource_group_name,
account_name=storage_account_name,
share_name=share_name,
file_share=FileShare(
share_quota=1 # Share size in GiB
# Add other file share properties here
)
)
可以使用该类配置文件共享属性 FileShare
。 上一个示例演示如何设置 share_quota
属性。 若要了解详细信息,请参阅 StorageManagementClient 类参考。
注释
若要执行注册操作,需要以下 Azure RBAC 操作的权限:Microsoft.Storage/register/action。 此权限包含在参与者和所有者内置角色中。
示例:使用 Azure 存储管理库列出文件共享和快照
以下代码示例演示如何列出存储帐户中的文件共享和快照:
from azure.identity import DefaultAzureCredential
from azure.mgmt.storage import StorageManagementClient
# Create the credential for authentication
credential = DefaultAzureCredential()
# Define variables
subscription_id = "<subscription-id>"
resource_group_name = "<resource-group-name>"
storage_account_name = "<storage-account-name>"
expand = "snapshots" # Include snapshots in the response
# Create storage management client
storage_client = StorageManagementClient(credential, subscription_id)
# List all file shares with their snapshots
file_shares = storage_client.file_shares.list(
resource_group_name=resource_group_name,
account_name=storage_account_name,
expand=expand
)
# Iterate over the file shares and print them along with any snapshots
for share in file_shares:
print(f"Resource name: {share.name}")
if share.snapshot_time:
print(f"Snapshot: {share.snapshot_time}")
相关内容
有关使用 Azure 文件进行开发的详细信息,请参阅以下资源: