✔️ 適用於: 使用 Microsoft.Storage 資源提供者建立的經典 SMB 和 NFS 檔案共享。
✖️ 不適用於:使用 Microsoft.FileShares 資源提供者建立的檔案共用
學習如何開發使用 Azure 檔案儲存體 來儲存資料的 Python 應用程式。 Azure 檔案儲存體 是一個雲端管理式檔案分享服務。 它提供可透過業界標準伺服器消息塊 (SMB) 和網路文件系統 (NFS) 通訊協定存取的完整受控檔案共用。 Azure 檔案儲存體 也提供一個 REST API,方便程式化存取檔案分享。
在本文中,您將了解使用 Python 開發 Azure 檔案儲存體 的不同方法,以及如何選擇最適合您應用程式需求的方法。 你也會學習如何建立一個基本的主控台應用程式,能與 Azure 檔案儲存體 資源互動。
關於使用 Azure 檔案儲存體 進行 Python 應用程式開發
Azure 檔案儲存體 提供多種方式讓 Python 開發者存取資料並管理 Azure 檔案儲存體 中的資源。 下表列出這些方法、摘要說明其運作方式,並提供使用每個方法時機的指引:
| 方法 | 運作方式 | 使用時機 |
|---|---|---|
| 標準檔案輸入/輸出函式庫 | 使用透過 SMB 或 NFS 掛載的 Azure 檔案分享進行作業系統層級的 API 呼叫。 當你使用 SMB/NFS 掛載檔案分享時,可以使用程式語言或框架的檔案 I/O 函式庫,例如 os 和 io 用於 Python。 |
你有業務線應用程式,已有使用標準檔案輸入輸出的程式碼,你不想為了讓應用程式能與 Azure 檔案分享相容而重寫程式碼。 |
| 檔案REST API | 直接呼叫 HTTPS 端點來與儲存在 Azure 檔案儲存體 中的資料互動。 提供檔案共用資源的程序設計控制。 Azure SDK 提供了建立在 FileREST API 上的檔案共享用戶端函式庫(FileREST Library (azure-storage-file-share),因此你可以透過熟悉的 Python 程式語言範例與 FileREST API 操作互動。 |
你要為客戶打造增值的雲端服務和應用程式,並且想使用Python檔案I/O函式庫無法提供的進階功能。 |
| 記憶體資源提供者 REST API | 使用 Azure Resource Manager(ARM)來管理儲存帳號和檔案分享。 針對各種資源管理作業呼叫 REST API 端點。 | 您的應用程式或服務必須執行資源管理工作,例如建立、刪除或更新記憶體帳戶或檔案共用。 |
關於這些方法的一般資訊,請參見 應用開發概述,Azure 檔案儲存體。
本文著重於運用以下方法來操作 Azure 檔案儲存體 資源:
- 使用 Python 檔案 I/O 函式庫 與Azure 檔案儲存體合作:使用 SMB 或 NFS 掛載檔案分享,並使用 Python 檔案 I/O 函式庫來處理該共享中的檔案與目錄。
- 使用 Azure 檔案儲存體 用戶端函式庫來與 Python 一起操作檔案共享:使用 Azure 儲存體 File Shares 用戶端函式庫來處理檔案共享中的檔案與目錄。 此用戶端連結庫建置在 FileREST API 上。
- 使用 Azure 儲存體 管理函式庫管理Azure 檔案儲存體資源:使用Azure 儲存體管理函式庫來管理儲存帳號中的檔案分享及其他資源。 管理函式庫建構於 Azure 儲存體 資源提供者 REST API。
先決條件
- Azure訂閱 - 免費創建一個
- Azure 儲存帳號 - 建立儲存帳號
- Python 3.8+
設定您的專案
本節將引導你準備專案以使用 Azure 檔案儲存體。
從您的項目目錄中,使用 pip install 命令,根據應用程式的需求來安裝套件。 以下範例展示了如何安裝 Azure 檔案共享客戶端函式庫、儲存管理客戶端函式庫,以及 Azure 身份函式庫。
azure-identity 套件用於無密碼連接Azure服務。
pip install azure-identity
pip install azure-storage-file-share
pip install azure-mgmt-resource
pip install azure-mgmt-storage
開啟您的程式碼檔案,並新增必要的匯入陳述式。
如果你打算使用 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 函式庫:
- App 相容性: 非常適合業務應用程式,其現有代碼已使用 Python 檔案 I/O 函式庫。 你不需要重寫程式碼讓應用程式能與 Azure 檔案分享相容。
- 易用性: Python 檔案 I/O 函式庫在開發者間廣為人知且易於使用。 Azure 檔案儲存體 的一大價值主張是它透過 SMB 和 NFS 公開原生檔案系統 API。
在本節中,您將學習如何使用 Python 檔案 I/O 函式庫來處理 Azure 檔案儲存體 資源。
如需詳細資訊和範例,請參閱下列資源:
- Python檔案 I/O 函式庫:
os 和io
掛接檔案共用
要使用 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 的 File Shares 用戶端函式庫處理 Azure 檔案儲存體 資料
FileREST API 提供對 Azure 檔案儲存體的程式設計存取權。 它可讓您呼叫 HTTPS 端點,以在檔案共享、目錄和檔案上執行作業。 FileREST API 是針對可能無法透過原生通訊協定使用的高延展性和進階功能所設計。 Azure SDK 提供客戶端函式庫,例如 Python 的 File Shares 用戶端函式庫,這些函式庫建構在 FileREST API 之上。
如果您的應用程式需要以下條件,請考慮使用 FileREST API 和 File Shares 用戶端函式庫:
- 進階功能: 存取無法透過原生通訊協定使用的各項操作與功能。
- 自訂雲端整合: 建立自訂增值服務,如備份、防毒或資料管理,直接與Azure 檔案儲存體互動。
- 效能優化: 使用資料平面操作,在大規模情境中受益於效能優勢。
FileREST API 將 Azure 檔案儲存體 建模為資源階層。 用它來執行你在 目錄 或 檔案 層級執行的操作。 對於在 檔案服務 或 檔案分享 層級執行的操作,請使用 Storage resource provider REST API。
在本節中,您將學習如何使用 File Sharing 用戶端函式庫來操作 Azure 檔案儲存體 資源。
如需詳細資訊和範例,請參閱下列資源:
Azure 儲存檔案共享 Python 用戶端函式庫 - Azure 儲存體 檔案共享客戶端函式庫,提供Python範例
授權存取並建立用戶端
要將應用程式連接到 Azure 檔案儲存體,請建立一個 ShareClient 物件。 這個物件是你使用 Azure 檔案儲存體 資源的起點。 下列程式代碼範例示範如何使用不同的授權機制來建立 ShareClient 物件。
要用 Microsoft Entra ID 授權,你需要使用安全原則。 您需要的安全性主體類型取決於您的應用程式執行位置。 請使用下表作為指南。
| 應用程式的執行位置 | 安全性主體 | 指導 |
|---|---|---|
| 本機電腦 (開發和測試) | 服務主體 | 要了解如何註冊應用程式、建立Microsoft Entra群組、指派角色以及設定環境變數,請參見 Authorize access using developer service principals |
| 本機電腦 (開發和測試) | 使用者身分識別 | 想了解如何建立Microsoft Entra群組、指派角色以及登入Azure,請參考 Authorize access using developer credentials |
| 以 Azure 托管 | 受管理的識別 | 欲了解如何啟用受管理身份並指派角色,請參閱 使用受管理身份授權 Azure 託管應用程式的存取 |
| 託管在 Azure 外部(例如本地部署的應用程式) | 服務主體 | 若要了解如何註冊應用程式、指派角色及設定環境變數,請參閱 使用應用程式服務主體從内部部署應用程式授權存取 |
要處理本文中的程式碼範例,請將 Azure RBAC 內建角色 Storage File Data Privileged Contributor 指派給安全主體。 不論已設定的檔案/目錄層級NTFS許可權為何,此角色都會針對所有已設定的記憶體帳戶,提供共用中所有資料的完整讀取、寫入、修改 ACL 和刪除存取權。 欲了解更多資訊,請參閱 使用 Microsoft Entra ID 和 Azure 檔案儲存體 OAuth 透過 REST 存取 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 的
若要深入瞭解每個授權機制,請參閱 選擇如何授權檔案數據的存取權。
範例:使用檔案共享用戶端連結庫複製檔案
您可以使用下列方法,在檔案共用內或檔案共享之間複製檔案:
您可以從 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 儲存體。
利用Azure 儲存體管理函式庫管理Azure 檔案儲存體資源
Azure 儲存體 管理函式庫是建立在 Azure 儲存體 資源提供者 REST API 之上。 Azure 儲存體資源提供者是基於 Azure Resource Manager 的服務,支援宣告式(範本)與命令式(直接 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 檔案儲存體 開發的資訊,請參閱以下資源:
使用 Azure 檔案儲存體 - 命名及參考共用、目錄、檔案和中繼資料
- 管理檔案鎖定
- 目錄上的作業
- 檔案上的作業