Python での Azure Files 用の開発

ファイル データの格納に Azure Files を使用するアプリまたはサービスを開発するための Python の基本的な使い方について説明します。 コンソール アプリを作成し、Python と Azure Files を使用した基本アクションの実行方法を確認します。

  • Azure ファイル共有を作成する
  • ディレクトリを作成する
  • Azure ファイル共有のファイルとディレクトリを列挙する
  • ファイルのアップロード、ダウンロード、および削除
  • スナップショットを使用してファイル共有バックアップを作成する

Note

Azure Files は SMB 経由でアクセスできるため、ファイル I/O の標準 Python I/O クラスと関数を使って Azure ファイル共有にアクセスする簡単なアプリケーションを作成できます。 この記事では、Azure Storage SDK for Python を使用するアプリを記述する方法を説明します。これは、Azure Files との通信に Azure Files REST API を使用します。

適用対象

ファイル共有の種類 SMB NFS
Standard ファイル共有 (GPv2)、LRS/ZRS Yes No
Standard ファイル共有 (GPv2)、GRS/GZRS Yes No
Premium ファイル共有 (FileStorage)、LRS/ZRS Yes No

Microsoft Azure Storage SDK for Python をダウンロードしてインストールする

Note

Azure Storage SDK for Python 0.36 以前のバージョンからアップグレードする場合は、pip uninstall azure-storage を使用して以前の SDK をアンインストールしてから、最新のパッケージをインストールします。

Python 用 Azure Files クライアント ライブラリには、Python 3.8 以降が必要です。

PyPI でインストールする

Python Package Index (PyPI) でインストールするには、次のように入力します。

pip install azure-storage-file-share

Azure Files を使用するようにアプリケーションを設定する

この記事のコード スニペットを使用するには、Python ソース ファイルの先頭近くに次のコードを追加します。

from azure.core.exceptions import (
    ResourceExistsError,
    ResourceNotFoundError
)

from azure.storage.fileshare import (
    ShareServiceClient,
    ShareClient,
    ShareDirectoryClient,
    ShareFileClient
)

Azure Files への接続を設定する

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 Files にファイルをアップロードする方法について説明します。

次のメソッドでは、指定されたファイルの内容が、指定された 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_sharedelete_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 Files を操作する方法を習得したので、詳細について次のリンクを参照してください。

非推奨の Python バージョン 2 SDK を使用する関連コード サンプルについては、「Python バージョン 2 を使用したコード サンプル」を参照してください。