此示例演示了如何在 Python 应用程序代码中使用 Azure 客户端库,以便将文件上传到 Blob 存储容器。 本示例假定你已创建 示例:创建 Azure 存储 中显示的资源。

除非另行说明,否则本文中的所有资源在 Linux/macOS bash 和 Windows 命令行界面上的工作方式相同。

1:设置本地开发环境

如果尚未设置,请设置一个可在其中运行此代码的环境。 提供以下选择:

  • 配置 Python 虚拟环境 。 可以在本地或 Azure Cloud Shell 中创建虚拟环境,并在其中运行代码。 请务必激活虚拟环境以开始使用它。

  • 使用 conda 环境

  • Visual Studio Code GitHub Codespaces 中使用 开发容器

    2:安装库包

    requirements.txt 文件中,为要使用的客户端库包添加行并保存文件。

    azure-storage-blob azure-identity

    然后,在终端或命令提示符下,安装要求。

    pip install -r requirements.txt
    

    3:创建要上传的文件

    创建名为 sample-source.txt的源文件。 此文件名是代码所需的名称。

    Hello there, Azure Storage. I'm a friendly file ready to be stored in a blob.

    4:通过应用代码使用 Blob 存储

    以下两部分演示了访问通过示例创建的 Blob 容器的两种方法 :创建 Azure 存储

    使用 身份验证) (的第一种方法 使用 DefaultAzureCredential 对应用进行身份验证,如 使用 DefaultAzureCredential 对 Azure 托管应用程序进行身份验证中所述。 使用此方法时,必须先为应用标识分配适当的权限,这是建议的做法。

    二种方法 (连接字符串) 使用连接字符串直接访问存储帐户。 尽管此方法看起来更简单,但它有两个重大缺点:

  • 连接字符串在本质上使用存储帐户(而不是该帐户中的单个资源)来验证连接代理。 因此,连接字符串提供的授权范围超出了所需的权限。

  • 连接字符串包含纯文本访问信息,因此,如果构造不当或保护不当,则存在潜在的漏洞。 如果公开了此类连接字符串,则可用于访问存储帐户中的各种资源。

    出于这些原因,建议在生产代码中使用该身份验证方法。

    4a:将 Blob 存储与身份验证配合使用

  • 创建名为 AZURE_STORAGE_BLOB_URL 的环境变量:

    将“pythonazurestorage12345”替换为特定存储帐户的名称。

    AZURE_STORAGE_BLOB_URL 环境变量仅在本例中使用,Azure 库没有使用它。

  • 使用以下代码创建一个名为“use_blob_auth py”的文件。 注释对步骤进行了说明。

    import os import uuid from azure.identity import DefaultAzureCredential # Import the client object from the SDK library from azure.storage.blob import BlobClient credential = DefaultAzureCredential() # Retrieve the storage blob service URL, which is of the form # https://<your-storage-account-name>.blob.core.windows.net/ storage_url = os.environ["AZURE_STORAGE_BLOB_URL"] # Create the client object using the storage URL and the credential blob_client = BlobClient( storage_url, container_name="blob-container-01", blob_name=f"sample-blob-{str(uuid.uuid4())[0:5]}.txt", credential=credential, # Open a local file and upload its contents to Blob Storage with open("./sample-source.txt", "rb") as data: blob_client.upload_blob(data) print(f"Uploaded sample-source.txt to {blob_client.url}")

    参考链接:

  • DefaultAzureCredential (azure.identity)
  • BlobClient (azure.storage.blob)
  • 尝试运行代码(有意失败):

    python use_blob_auth.py
    
  • 请注意错误“此请求无权使用此权限执行此操作”。出现此错误是因为所使用的本地服务主体尚没有访问 Blob 容器的权限。

  • 使用 Azure CLI 命令 az role assignment create(此命令较长!)将容器权限授予服务主体:

    az role assignment create --assignee <AZURE_CLIENT_ID> ^
        --role "Storage Blob Data Contributor" ^
        --scope "/subscriptions/<AZURE_SUBSCRIPTION_ID>/resourceGroups/PythonAzureExample-Storage-rg/providers/Microsoft.Storage/storageAccounts/pythonazurestorage12345/blobServices/default/containers/blob-container-01"
    
    az role assignment create --assignee <AZURE_CLIENT_ID> \
        --role "Storage Blob Data Contributor" \
        --scope "/subscriptions/<AZURE_SUBSCRIPTION_ID>/resourceGroups/PythonAzureExample-Storage-rg/providers/Microsoft.Storage/storageAccounts/pythonazurestorage12345/blobServices/default/containers/blob-container-01"
    

    --scope 参数标识此角色分配适用的位置。 在此示例中,将“存储 Blob 数据参与者”角色授予名为“blob-container-01”的特定容器。

    将 和 pythonazurestorage12345 替换为PythonAzureExample-Storage-rg包含存储帐户和存储帐户确切名称的资源组。 此外,如有必要,请调整资源组和 Blob 容器的名称。 如果使用错误名称,会发现错误“无法对嵌套资源执行请求的操作。 找不到父资源‘pythonazurestorage12345’”。

    --scope此命令中的 参数还使用 <AZURE_CLIENT_ID> 和 <AZURE_SUBSCRIPTION_ID> 变量。 可以直接在命令中指定它们,也可以使用环境变量指定它们。 如果使用环境变量,稍后可能会在再次运行代码时看到有关环境配置不完整的警告。

    如果在使用 bash shell 时角色分配命令返回错误“找不到连接适配器”,请尝试设置 export MSYS_NO_PATHCONV=1 以避免路径转换。 有关详细信息,请参阅 此问题

  • 花一两分钟时间等待权限传播,然后再次运行该代码,验证它现在是否正常工作。 如果再次看到权限错误,请等待更长的时间,然后重试代码。

    有关角色分配的详细信息,请参阅如何使用 Azure CLI 分配角色权限

    4b:将 blob 存储与连接字符串配合使用

  • 创建一个名为 AZURE_STORAGE_CONNECTION_STRING 的环境变量,其值是存储帐户的完整连接字符串。 (此环境变量还由各种 Azure CLI 注释使用。)

  • 创建包含以下代码的名为“use_blob_conn_string.py”的 Python 文件。 注释对步骤进行了说明。

    import os import uuid # Import the client object from the SDK library from azure.storage.blob import BlobClient # Retrieve the connection string from an environment variable. Note that a # connection string grants all permissions to the caller, making it less # secure than obtaining a BlobClient object using credentials. conn_string = os.environ["AZURE_STORAGE_CONNECTION_STRING"] # Create the client object for the resource identified by the connection # string, indicating also the blob container and the name of the specific # blob we want. blob_client = BlobClient.from_connection_string( conn_string, container_name="blob-container-01", blob_name=f"sample-blob-{str(uuid.uuid4())[0:5]}.txt", # Open a local file and upload its contents to Blob Storage with open("./sample-source.txt", "rb") as data: blob_client.upload_blob(data) print(f"Uploaded sample-source.txt to {blob_client.url}")
  • 运行代码:

    python use_blob_conn_string.py
    

    同样,虽然此方法很简单,但连接字符串会授权存储帐户中的所有操作。 使用生产代码时,最好使用上一节中所述的特定权限。

    5.验证 blob 创建

    运行任一方法的代码后,请转到Azure 门户,导航到 blob 容器,验证是否存在名为 sample-blob-{random}的新 blob .txt,其内容与 sample-source.txt 文件相同:

    如果创建了名为 的 AZURE_STORAGE_CONNECTION_STRING环境变量,还可以使用 Azure CLI 使用 az storage blob list 命令验证 Blob 是否存在:

    az storage blob list --container-name blob-container-01
    

    6:清理资源

    az group delete -n PythonAzureExample-Storage-rg  --no-wait
    

    如果不需要保留此示例中创建的资源组,请运行 az group delete 命令。 资源组不会在你的订阅中产生任何持续的费用,但最好清除你不会主动使用的任何组。 --no-wait 参数允许命令立即返回,而不是等到操作完成再返回。

    你还可以使用 ResourceManagementClient.resource_groups.begin_delete 方法从代码中删除资源组。 示例:创建资源组中的代码演示了使用情况。

  • 示例:创建资源组
  • 示例:列出订阅中的资源组
  • 示例:创建 Web 应用并部署代码
  • 示例:创建 Azure 存储
  • 示例:创建和查询数据库
  • 示例:创建虚拟机
  • 将 Azure 托管磁盘与虚拟机一起使用
  • 完成有关 Azure SDK for Python 的简短调查
  •