共用方式為


使用 Python 開發 Azure 檔案儲存體

瞭解如何開發使用 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 檔案服務中的資源。 下表列出這些方法、摘要說明其運作方式,並提供使用每個方法時機的指引:

方法 運作方式 使用時機
標準檔案輸入/輸出函式庫 透過使用 SMB 或 NFS 掛載的 Azure 檔案共用使用作業系統層級的 API 呼叫。 當您使用 SMB/NFS 掛載檔案共享時,可以使用程式設計語言或框架中的檔案 I/O 函式庫,例如 Python 的 osio 您有具有使用標準檔案 I/O 之現有程式代碼的企業營運應用程式,而且您不想要重寫程式代碼,讓應用程式使用 Azure 檔案共用。
FileREST API 直接呼叫 HTTPS 端點,以與儲存在 Azure 檔案服務中的數據互動。 提供檔案共用資源的程序設計控制。 Azure SDK 提供以 FileREST API 為基礎的檔案共用用戶端連結庫 (azure-storage-file-share),可讓您透過熟悉的 Python 程式設計語言範例與 FileREST API 作業互動。 您要為客戶建置增值的雲端服務和應用程式,而且想要使用無法透過 Python 檔案 I/O 連結庫取得的進階功能。
記憶體資源提供者 REST API 使用 Azure Resource Manager (ARM) 來管理記憶體帳戶和檔案共用。 針對各種資源管理作業呼叫 REST API 端點。 您的應用程式或服務必須執行資源管理工作,例如建立、刪除或更新記憶體帳戶或檔案共用。

如需這些方法的一般資訊,請參閱 使用 Azure 檔案服務開發應用程式的概觀

本文著重於使用下列方法使用 Azure 檔案服務資源:

先決條件

設定您的專案

本節將逐步引導您準備專案以使用 Azure 檔案服務。

從您的項目目錄中,使用 pip install 命令,根據應用程式的需求來安裝套件。 下列範例示範如何安裝 Azure 檔案共用用戶端連結庫、記憶體管理客戶端連結庫和 Azure 身分識別連結庫。 需要 azure 身分識別 套件才能對 Azure 服務進行無密碼連線。

pip install azure-identity
pip install azure-storage-file-share
pip install azure-mgmt-resource
pip install azure-mgmt-storage

開啟您的程式碼檔案,並新增必要的匯入陳述式。

如果您打算使用 Python osio 庫,請將下列內容新增至 .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 連結庫,例如 osio,與共用中的檔案和目錄互動。

當您的應用程式需要時,請考慮使用 Python 檔案 I/O 連結庫:

  • 應用程式相容性: 適用於已使用 Python 檔案 I/O 連結庫的現有程式代碼的企業營運應用程式。 您不需要重寫程式代碼,應用程式即可使用 Azure 檔案共用。
  • 易於使用: Python 檔案 I/O 連結庫是由開發人員所熟知,而且容易使用。 Azure 檔案服務的重要價值主張是,它會透過 SMB 和 NFS 公開原生文件系統 API。

在本節中,您將瞭解如何使用 Python 檔案 I/O 連結庫來處理 Azure 檔案資源。

如需詳細資訊和範例,請參閱下列資源:

  • 檔案 I/O 的 Python 連結庫: osio

掛接檔案共用

若要使用 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 Files 資料

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 內建角色 記憶體檔案數據特殊許可權參與者 指派給安全性主體。 不論已設定的檔案/目錄層級NTFS許可權為何,此角色都會針對所有已設定的記憶體帳戶,提供共用中所有資料的完整讀取、寫入、修改 ACL 和刪除存取權。 如需詳細資訊,請參閱 透過 REST 使用 Microsoft Entra ID 搭配 Azure 檔案記憶體 OAuth 存取 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)

範例:使用檔案共享用戶端連結庫租用檔案

租用會透過租用識別碼對 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 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 檔案服務開發的詳細資訊,請參閱下列資源: