開發使用 Azure 檔案儲存體 的 Python 應用程式
了解使用 Python 以開發使用 Azure 檔案儲存體來儲存檔案資料的應用程式或服務的基本概念。 建立主控台應用程式,並了解如何使用 Python 和 Azure 檔案儲存體來執行基本動作:
- 建立 Azure 檔案共用
- 建立目錄
- 列舉 Azure 檔案共用的檔案和目錄
- 上傳、下載及刪除檔案
- 使用快照集建立檔案共用備份
注意
因為 Azure 檔案儲存體 可能透過SMB存取,所以可以使用標準 Python I/O 類別和函式來撰寫存取 Azure 檔案共用的簡單應用程式。 本文說明如何撰寫使用適用於 Python Azure 儲存體 SDK 的應用程式,其會使用 Azure 檔案儲存體 REST API 與 Azure 檔案儲存體 通訊。
適用於
檔案共用類型 | SMB | NFS |
---|---|---|
標準檔案共用 (GPv2)、LRS/ZRS | ||
標準檔案共用 (GPv2)、GRS/GZRS | ||
進階檔案共用 (FileStorage)、LRS/ZRS |
下載並安裝 Azure Storage SDK for Python
注意
如果您要從適用於 Python 0.36 版或更早版本的 Azure 儲存體 SDK 升級,請先卸載舊版 SDKpip uninstall azure-storage
,再安裝最新的套件。
適用於 Python 的 Azure 檔案儲存體用戶端程式庫 需要 Python 3.8+。
透過 PyPI 安裝
若要透過 Python Package Index (PyPI) 安裝,請輸入:
pip install azure-storage-file-share
設定您的應用程式以使用 Azure 檔案服務
將下列程式碼新增至 Python 來源檔案靠近頂端的位置,以使用此文章中的程式碼片段。
from azure.core.exceptions import (
ResourceExistsError,
ResourceNotFoundError
)
from azure.storage.fileshare import (
ShareServiceClient,
ShareClient,
ShareDirectoryClient,
ShareFileClient
)
設定 Azure 檔案服務的連線
ShareServiceClient 可讓您使用共用、目錄和檔案。 此程式碼使用儲存體帳戶連接字串來建立 ShareServiceClient
物件:
# Create a ShareServiceClient from a connection string
service_client = ShareServiceClient.from_connection_string(connection_string)
建立 Azure 檔案共用
下列程式碼範例使用 ShareClient 物件來建立共用 (如果共用不存在)。
def create_file_share(self, connection_string, share_name):
try:
# Create a ShareClient from a connection string
share_client = ShareClient.from_connection_string(
connection_string, share_name)
print("Creating share:", share_name)
share_client.create_share()
except ResourceExistsError as ex:
print("ResourceExistsError:", ex.message)
建立目錄
您可以組織儲存體,方法是將檔案放在子目錄中,而不是將所有檔案都放在根目錄中。
下列方法使用 ShareDirectoryClient 物件,在指定檔案共用的根目錄中建立目錄。
def create_directory(self, connection_string, share_name, dir_name):
try:
# Create a ShareDirectoryClient from a connection string
dir_client = ShareDirectoryClient.from_connection_string(
connection_string, share_name, dir_name)
print("Creating directory:", share_name + "/" + dir_name)
dir_client.create_directory()
except ResourceExistsError as ex:
print("ResourceExistsError:", ex.message)
上傳檔案
在此節中,您將了解如何將檔案從本機儲存體上傳至 Azure 檔案儲存體。
下列方法會將指定檔案的內容上傳至指定 Azure 檔案共用中的指定目錄。
def upload_local_file(self, connection_string, local_file_path, share_name, dest_file_path):
try:
source_file = open(local_file_path, "rb")
data = source_file.read()
# Create a ShareFileClient from a connection string
file_client = ShareFileClient.from_connection_string(
connection_string, share_name, dest_file_path)
print("Uploading to:", share_name + "/" + dest_file_path)
file_client.upload_file(data)
except ResourceExistsError as ex:
print("ResourceExistsError:", ex.message)
except ResourceNotFoundError as ex:
print("ResourceNotFoundError:", ex.message)
列舉 Azure 檔案共用的檔案和目錄
若要列出子目錄中的檔案和目錄,請使用 list_directories_and_files 方法。 此方法會傳回自動分頁的可反覆執行物件。 下列程式碼會將指定目錄中每個檔案和子目錄的名稱輸出到主控台。
def list_files_and_dirs(self, connection_string, share_name, dir_name):
try:
# Create a ShareClient from a connection string
share_client = ShareClient.from_connection_string(
connection_string, share_name)
for item in list(share_client.list_directories_and_files(dir_name)):
if item["is_directory"]:
print("Directory:", item["name"])
else:
print("File:", dir_name + "/" + item["name"])
except ResourceNotFoundError as ex:
print("ResourceNotFoundError:", ex.message)
下載檔案
若要從檔案下載資料,請使用 download_file。
下列範例示範如何使用 download_file
來取得指定檔案的內容,然後將其儲存在本機,並在檔案名稱前面加上 DOWNLOADED-。
def download_azure_file(self, connection_string, share_name, dir_name, file_name):
try:
# Build the remote path
source_file_path = dir_name + "/" + file_name
# Add a prefix to the filename to
# distinguish it from the uploaded file
dest_file_name = "DOWNLOADED-" + file_name
# Create a ShareFileClient from a connection string
file_client = ShareFileClient.from_connection_string(
connection_string, share_name, source_file_path)
print("Downloading to:", dest_file_name)
# Open a file for writing bytes on the local system
with open(dest_file_name, "wb") as data:
# Download the file from Azure into a stream
stream = file_client.download_file()
# Write the stream to the local file
data.write(stream.readall())
except ResourceNotFoundError as ex:
print("ResourceNotFoundError:", ex.message)
建立共用快照集
您可以針對整個檔案共用,建立一個時間點複本。
def create_snapshot(self, connection_string, share_name):
try:
# Create a ShareClient from a connection string
share_client = ShareClient.from_connection_string(
connection_string, share_name)
# Create a snapshot
snapshot = share_client.create_snapshot()
print("Created snapshot:", snapshot["snapshot"])
# Return the snapshot time so
# it can be accessed later
return snapshot["snapshot"]
except ResourceNotFoundError as ex:
print("ResourceNotFoundError:", ex.message)
列出共用和快照集
您可以針對特定的共用,列出所有快照集。
def list_shares_snapshots(self, connection_string):
try:
# Create a ShareServiceClient from a connection string
service_client = ShareServiceClient.from_connection_string(connection_string)
# List the shares in the file service
shares = list(service_client.list_shares(include_snapshots=True))
for share in shares:
if (share["snapshot"]):
print("Share:", share["name"], "Snapshot:", share["snapshot"])
else:
print("Share:", share["name"])
except ResourceNotFoundError as ex:
print("ResourceNotFoundError:", ex.message)
瀏覽共用快照集
您可以瀏覽每個共用快照集,以擷取該時間點的檔案和目錄。
def browse_snapshot_dir(self, connection_string, share_name, snapshot_time, dir_name):
try:
# Create a ShareClient from a connection string
snapshot = ShareClient.from_connection_string(
conn_str=connection_string, share_name=share_name, snapshot=snapshot_time)
print("Snapshot:", snapshot_time)
for item in list(snapshot.list_directories_and_files(dir_name)):
if item["is_directory"]:
print("Directory:", item["name"])
else:
print("File:", dir_name + "/" + item["name"])
except ResourceNotFoundError as ex:
print("ResourceNotFoundError:", ex.message)
從共用快照集取得檔案
您可以從共用快照集下載檔案,這可讓您還原舊版檔案。
def download_snapshot_file(self, connection_string, share_name, snapshot_time, dir_name, file_name):
try:
# Build the remote path
source_file_path = dir_name + "/" + file_name
# Add a prefix to the local filename to
# indicate it's a file from a snapshot
dest_file_name = "SNAPSHOT-" + file_name
# Create a ShareFileClient from a connection string
snapshot_file_client = ShareFileClient.from_connection_string(
conn_str=connection_string, share_name=share_name,
file_path=source_file_path, snapshot=snapshot_time)
print("Downloading to:", dest_file_name)
# Open a file for writing bytes on the local system
with open(dest_file_name, "wb") as data:
# Download the file from Azure into a stream
stream = snapshot_file_client.download_file()
# Write the stream to the local file
data.write(stream.readall())
except ResourceNotFoundError as ex:
print("ResourceNotFoundError:", ex.message)
刪除單一共用快照集
您可以刪除單一共用快照集。
def delete_snapshot(self, connection_string, share_name, snapshot_time):
try:
# Create a ShareClient for a snapshot
snapshot_client = ShareClient.from_connection_string(conn_str=connection_string, share_name=share_name, snapshot=snapshot_time)
print("Deleting snapshot:", snapshot_time)
# Delete the snapshot
snapshot_client.delete_share()
except ResourceNotFoundError as ex:
print("ResourceNotFoundError:", ex.message)
刪除檔案
若要刪除檔案,請呼叫 delete_file。
def delete_azure_file(self, connection_string, share_name, file_path):
try:
# Create a ShareFileClient from a connection string
file_client = ShareFileClient.from_connection_string(
connection_string, share_name, file_path)
print("Deleting file:", share_name + "/" + file_path)
# Delete the file
file_client.delete_file()
except ResourceNotFoundError as ex:
print("ResourceNotFoundError:", ex.message)
共用快照集存在時刪除共用
若要刪除包含快照集的共用,請使用 delete_share 搭配 delete_snapshots=True
。
def delete_share(self, connection_string, share_name):
try:
# Create a ShareClient from a connection string
share_client = ShareClient.from_connection_string(
connection_string, share_name)
print("Deleting share:", share_name)
# Delete the share and snapshots
share_client.delete_share(delete_snapshots=True)
except ResourceNotFoundError as ex:
print("ResourceNotFoundError:", ex.message)
下一步
您現在已經學會如何使用 Python 操作 Azure 檔案服務,請遵循這些連結深入了解。
如需使用已取代的 Python 2 版 SDK 相關程式碼範例,請參閱使用 Python 2 版的程式碼範例。