Share via


Desenvolver aplicativos Python que usam Arquivos do Azure

Aprenda as noções básicas do uso do Python para desenvolver aplicativos ou serviços que usam os Arquivos do Azure para armazenar dados de arquivos. Crie um aplicativo de console e saiba como executar ações básicas com Python e Arquivos do Azure:

  • Criar compartilhamentos de arquivos do Azure
  • Criar diretórios
  • Enumerar arquivos e diretórios em um compartilhamento de arquivos do Azure
  • Carregar, transferir e eliminar um ficheiro
  • Crie backups de compartilhamento de arquivos usando instantâneos

Nota

Como os Arquivos do Azure podem ser acessados por SMB, é possível escrever aplicativos simples que acessam o compartilhamento de arquivos do Azure usando as classes e funções de E/S Python padrão. Este artigo descreve como escrever aplicativos que usam o SDK de Armazenamento do Azure para Python, que usa a API REST dos Arquivos do Azure para falar com os Arquivos do Azure.

Aplica-se a

Tipo de partilhas de ficheiros SMB NFS
Partilhas de ficheiros Standard (GPv2), LRS/ZRS Yes No
Partilhas de ficheiros Standard (GPv2), GRS/GZRS Yes No
Partilhas de ficheiros Premium (FileStorage), LRS/ZRS Yes No

Baixar e instalar o SDK de Armazenamento do Azure para Python

Nota

Se você estiver atualizando do SDK de Armazenamento do Azure para Python versão 0.36 ou anterior, desinstale o SDK mais antigo usando pip uninstall azure-storage antes de instalar o pacote mais recente.

A biblioteca de cliente do Azure Files para Python requer Python 3.8+.

Instalar via PyPI

Para instalar através do Python Package Index (PyPI), digite:

pip install azure-storage-file-share

Configurar seu aplicativo para usar o Azure Files

Adicione o seguinte código perto da parte superior de um arquivo de origem Python para usar os trechos de código neste artigo.

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

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

Configurar uma ligação aos Ficheiros do Azure

ShareServiceClient permite que você trabalhe com compartilhamentos, diretórios e arquivos. Este código cria um ShareServiceClient objeto usando a cadeia de conexão da conta de armazenamento:

# Create a ShareServiceClient from a connection string
service_client = ShareServiceClient.from_connection_string(connection_string)

Criar uma partilha de ficheiros do Azure

O exemplo de código a seguir usa um objeto ShareClient para criar o compartilhamento se ele não existir.

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)

Criar um diretório

Você pode organizar o armazenamento colocando arquivos dentro de subdiretórios em vez de ter todos eles no diretório raiz.

O método a seguir cria um diretório na raiz do compartilhamento de arquivos especificado usando um objeto 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)

Carregar um ficheiro

Nesta seção, você aprenderá a carregar um arquivo do armazenamento local no Azure Files.

O método a seguir carrega o conteúdo do arquivo especificado no diretório especificado no compartilhamento de arquivos do Azure especificado.

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)

Enumerar arquivos e diretórios em um compartilhamento de arquivos do Azure

Para listar os arquivos e diretórios em um subdiretório, use o método list_directories_and_files . Esse método retorna uma paginação automática iterável. O código a seguir gera o nome de cada arquivo e subdiretório no diretório especificado para o console.

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)

Transferir um ficheiro

Para baixar dados de um arquivo, use download_file.

O exemplo a seguir demonstra o uso download_file para obter o conteúdo do arquivo especificado e armazená-lo localmente com DOWNLOADED- prepended para o nome do arquivo.

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)

Criar um instantâneo de partilha

Você pode criar uma cópia point-in-time de todo o compartilhamento de arquivos.

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)

Listar compartilhamentos e instantâneos

Você pode listar todos os instantâneos de um compartilhamento específico.

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)

Procurar instantâneo de compartilhamento

Você pode navegar em cada instantâneo de compartilhamento para recuperar arquivos e diretórios a partir desse momento.

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)

Obter arquivo do compartilhamento instantâneo

Você pode baixar um arquivo de um instantâneo de compartilhamento, que permite restaurar uma versão anterior de um arquivo.

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)

Excluir um único instantâneo de compartilhamento

Você pode excluir um único instantâneo de compartilhamento.

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)

Eliminar um ficheiro

Para excluir um arquivo, chame 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)

Excluir compartilhamento quando houver instantâneos de compartilhamento

Para excluir um compartilhamento que contém instantâneos, chame delete_share com 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)

Próximos passos

Agora que você aprendeu como manipular Arquivos do Azure com Python, siga estes links para saber mais.

Para exemplos de código relacionados usando SDKs Python versão 2 preteridos, consulte Exemplos de código usando Python versão 2.