Python을 사용하여 Azure Files 개발

Azure Files를 사용하여 파일 데이터를 저장하는 앱 또는 서비스를 Python을 사용하여 개발하는 데 필요한 기본 사항을 알아봅니다. 콘솔 앱을 만들고, Python 및 Azure Files을 사용하여 기본 작업을 수행하는 방법을 알아봅니다.

  • Azure 파일 공유 만들기
  • 디렉터리 만들기
  • Azure 파일 공유의 파일 및 디렉터리 열거
  • 파일 업로드, 다운로드 및 삭제
  • 스냅샷을 사용하여 파일 공유 백업 만들기

참고 항목

Azure Files는 SMB를 통해 액세스할 수 있기 때문에 표준 Python I/O 클래스 및 함수를 사용하여 Azure File 공유에 액세스하는 간단한 애플리케이션을 작성할 수 있습니다. 이 문서에서는 Azure Files REST API를 사용하여 Azure Files와 통신하는 Python용 Azure Storage SDK를 사용하는 앱을 작성하는 방법에 대해 설명합니다.

적용 대상

파일 공유 유형 SMB NFS
표준 파일 공유(GPv2), LRS/ZRS Yes No
표준 파일 공유(GPv2), GRS/GZRS Yes No
프리미엄 파일 공유(FileStorage), LRS/ZRS Yes No

Azure Storage SDK for Python 다운로드 및 설치

참고 항목

Azure Storage SDK for Python 버전 0.36 또는 이전 버전에서 업그레이드하는 경우 최신 패키지를 설치하기 전에 pip uninstall azure-storage를 사용하여 이전 SDK를 제거합니다.

Python용 Azure Files 클라이언트 라이브러리에는 Python 3.8 이상이 필요합니다.

PyPI를 통해 설치

PyPi(Python Package Index)를 통해 설치하려면 다음을 입력합니다.

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_snapshots=Truedelete_share를 호출합니다.

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를 사용하는 코드 샘플을 참조하세요.