適用于 Python 的 Azure 儲存體檔案共用用戶端程式庫 - 12.15.0 版
Azure 檔案共用儲存體提供雲端中完全受控的檔案共用,可透過業界標準 伺服器訊息區 (SMB) 通訊協定來存取。 Windows、Linux 和 macOS 的雲端部署或內部部署可同時掛接 Azure 檔案共用。 此外,透過 Azure 檔案同步可以在 Windows Server 上快取 Azure 檔案共用,以便在資料的使用位置附近快速存取。
Azure 檔案共用可以用來:
- 取代或補充內部部署檔案伺服器
- 「隨即轉移」應用程式
- 使用共用應用程式設定、診斷共用和開發/測試/偵錯工具來簡化雲端開發
| 原始程式碼套件 (PyPI) | 套件 (Conda) | API 參考檔 | 產品檔 | 樣品
開始使用
Prerequisites
- 需要 Python 3.7 或更新版本才能使用此套件。 如需詳細資訊,請參閱 Azure SDK for Python 版本支援原則上的頁面。
- 您必須擁有 Azure 訂 用 帳戶和 Azure 儲存體帳戶 ,才能使用此套件。
安裝套件
使用 pip安裝適用于 Python 的 Azure 儲存體檔案共用用戶端程式庫:
pip install azure-storage-file-share
建立儲存體帳戶
如果您想要建立新的儲存體帳戶,您可以使用Azure 入口網站、Azure PowerShell或Azure 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 PowerShell或Azure 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
根據您想要使用的授權類型而定,參數可能會以多種不同形式提供:
若要使用 共用存取簽章 (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)
若要使用儲存體帳戶 共用金鑰 (也稱為帳戶金鑰或存取金鑰) ,請提供金鑰作為字串。 您可以在 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 核心檔 。
不再需要非同步用戶端和認證時,應該關閉它們。 這些物件是非同步內容管理員,並定義非同步 close
方法。
用戶端
提供四個不同的用戶端來與檔案共用服務的各種元件互動:
- ShareServiceClient - 此用戶端代表與 Azure 儲存體帳戶本身的互動,並可讓您取得預先設定的用戶端實例,以存取內的檔案共用。 它提供作業來擷取和設定服務屬性,以及帳戶內的清單、建立和刪除共用。 若要在特定共用上執行作業,請使用
get_share_client
方法來擷取用戶端。 - ShareClient - 此用戶端代表與特定檔案共用的互動 (,這些共用尚未存在) ,並可讓您取得預先設定的用戶端實例,以存取其中的目錄和檔案。 它提供作業來建立、刪除、設定或建立共用的快照集,並包含建立和列舉其內目錄內容的作業。 若要在特定目錄或檔案上執行作業,請使用
get_directory_client
或get_file_client
方法來擷取用戶端。 - ShareDirectoryClient - 此用戶端代表與特定目錄 (的互動,這些目錄尚未存在) 。 它提供建立、刪除或列舉立即或巢狀子目錄內容的作業,並包含在其中建立和刪除檔案的作業。 對於與特定子目錄或檔案相關的作業,也可以使用 和
get_file_client
函式擷取該實體的get_subdirectory_client
用戶端。 - 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)
選用組態
可在用戶端和每個作業層級傳入的選擇性關鍵字引數。
重試原則設定
具現化用戶端以設定重試原則時,請使用下列關鍵字引數:
- 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
。
其他用戶端/每個作業組態
可在用戶端或個別作業上指定的其他選擇性組態關鍵字引數。
用戶端關鍵字引數:
- connection_timeout (int) :用戶端將等候建立與伺服器的連線的秒數。 預設值為 20 秒。
- read_timeout (int) :用戶端在連續讀取作業之間等候的秒數,以取得來自伺服器的回應。 這是通訊端層級逾時,不會受到整體資料大小的影響。 會自動重試用戶端讀取逾時。 預設值是 60 秒。
- 傳輸 (任何) :使用者提供的傳輸以傳送 HTTP 要求。
每個作業關鍵字引數:
- raw_response_hook (可呼叫) :指定的回呼會使用從服務傳回的回應。
- raw_request_hook (可呼叫) :指定的回呼會在傳送至服務之前使用要求。
- client_request_id (str) :選擇性使用者指定的要求識別。
- user_agent (str) :將自訂值附加至要與要求一起傳送的使用者代理程式標頭。
- logging_enable (bool) :啟用偵錯層級的記錄。 預設為 False。 也可以在用戶端層級傳入,以針對所有要求啟用它。
- logging_body (bool) :啟用記錄要求和回應本文。 預設為 False。 也可以在用戶端層級傳入,以針對所有要求啟用它。
- 標頭 (聽寫) :傳入自訂標頭做為索引鍵、值組。 例如
headers={'CustomValue': value}
疑難排解
一般
儲存體檔案用戶端會引發 Azure Core中定義的例外狀況。
此清單可用於參考,以攔截擲回的例外狀況。 若要取得例外狀況的特定錯誤碼,請使用 error_code
屬性,也就是 exception.error_code
。
記錄
此程式庫會使用標準記錄程式庫進行 記錄 。 HTTP 會話的基本資訊 (URL、標頭等。) 會記錄在 INFO 層級。
您可以在具有 引數的用戶端 logging_enable
上啟用詳細的 DEBUG 層級記錄,包括要求/回應主體和未回應標頭:
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 範例可供您使用。 這些範例提供使用儲存體檔案共用時常見之其他案例的範例程式碼:
file_samples_hello_world.py (非同步版本) - 本文中找到的範例:
- 用戶端建立
- 建立檔案共用
- 上傳檔案
file_samples_authentication.py (非同步版本) - 驗證和建立用戶端的範例:
- 從連接字串
- 從共用存取金鑰
- 從共用存取簽章權杖
file_samples_service.py (非同步版本) - 與檔案服務互動的範例:
- 取得和設定服務屬性
- 建立、列出和刪除共用
- 取得共用用戶端
file_samples_share.py (非同步版本) - 與檔案共用互動的範例:
- 建立共用快照集
- 設定共用配額和中繼資料
- 列出目錄和檔案
- 取得目錄或檔案用戶端以與特定實體互動
file_samples_directory.py (非同步版本) - 與目錄互動的範例:
- 建立目錄並新增檔案
- 建立和刪除子目錄
- 取得子目錄用戶端
file_samples_client.py (非同步版本) - 與檔案互動的範例:
- 建立、上傳、下載和刪除檔案
- 從 URL 複製檔案
其他文件
如需 Azure 檔案共用儲存體的詳細資訊,請參閱 azure 檔案共用儲存體檔 docs.microsoft.com。
參與
此專案歡迎參與和提供建議。 大部分的參與都要求您同意「參與者授權合約 (CLA)」,宣告您有權且確實授與我們使用投稿的權利。 如需詳細資料,請前往 https://cla.microsoft.com 。
當您提交提取要求時,CLA Bot 會自動判斷您是否需要提供 CLA,並適當地裝飾 PR (例如標籤、註解)。 請遵循 bot 提供的指示。 您只需要使用我們的 CLA 在所有存放庫上執行此動作一次。
此專案採用 Microsoft Open Source Code of Conduct (Microsoft 開放原始碼管理辦法)。 如需詳細資訊,請參閱管理辦法常見問題集,如有任何其他問題或意見請連絡 opencode@microsoft.com。
意見反應
https://aka.ms/ContentUserFeedback。
即將登場:在 2024 年,我們將逐步淘汰 GitHub 問題作為內容的意見反應機制,並將它取代為新的意見反應系統。 如需詳細資訊,請參閱:提交並檢視相關的意見反應