示例:使用用于 Python 的 Azure 库创建 Azure 存储

本文介绍如何使用适用于 Python 的 Azure 管理库创建资源组,以及 Azure 存储帐户和 Blob 存储容器。

预配这些资源后,请参阅“ 示例:使用 Azure 存储 ”了解如何使用 Python 中的 Azure 客户端库将文件上传到 Blob 容器。

本文后面列出了 bash 和 PowerShell 的 等效 Azure CLI 命令 。 如果想要使用 Azure 门户,请参阅 “创建 Azure 存储帐户 ”和 “创建 Blob 容器”。

1:设置本地开发环境

如果尚未设置,请设置一个可在其中运行代码的环境。 下面是一些选项:

  • 使用 venv 或所选工具配置 Python 虚拟环境。 若要开始使用虚拟环境,请务必激活它。 若要安装 python,请参阅 “安装 Python”。

    #!/bin/bash
    # Create a virtual environment
    python -m venv .venv
    # Activate the virtual environment
    source .venv/Scripts/activate # only required for Windows (Git Bash)
    
  • 使用 conda 环境。 若要安装 Conda,请参阅 “安装 Miniconda”。

  • Visual Studio CodeGitHub Codespaces中使用 开发容器

2:安装所需的 Azure 库包

  1. 在控制台中创建一个 requirements.txt 文件,其中列出了此示例中使用的管理库:

    azure-mgmt-resource
    azure-mgmt-storage
    azure-identity
    
  2. 在激活虚拟环境的控制台中,安装要求:

    pip install -r requirements.txt
    

3. 设置环境变量

在此步骤中,你将设置环境变量,以便在本文中的代码中使用。 代码使用 os.environ 方法来检索值。

#!/bin/bash
export AZURE_RESOURCE_GROUP_NAME=<ResourceGroupName> # Change to your preferred resource group name
export LOCATION=<Location> # Change to your preferred region
export AZURE_SUBSCRIPTION_ID=$(az account show --query id --output tsv)
export STORAGE_ACCOUNT_NAME=<StorageAccountName> # Change to your preferred storage account name
export CONTAINER_NAME=<ContainerName> # Change to your preferred container name

4:编写代码以创建存储帐户和 Blob 容器

在此步骤中,你将使用以下代码创建名为 provision_blob.py 的 Python 文件。 此 Python 脚本使用用于 Python 的 Azure SDK 管理库,使用用于 Python 的 Azure SDK 创建资源组、Azure 存储帐户和 Blob 容器。

import os, random

# Import the needed management objects from the libraries. The azure.common library
# is installed automatically with the other libraries.
from azure.identity import DefaultAzureCredential
from azure.mgmt.resource import ResourceManagementClient
from azure.mgmt.storage import StorageManagementClient
from azure.mgmt.storage.models import BlobContainer

# Acquire a credential object.
credential = DefaultAzureCredential()

# Retrieve subscription ID from environment variable.
subscription_id = os.environ["AZURE_SUBSCRIPTION_ID"]

# Retrieve resource group name and ___location from environment variables
RESOURCE_GROUP_NAME = os.environ["AZURE_RESOURCE_GROUP_NAME"]
LOCATION = os.environ["LOCATION"]

# Step 1: Provision the resource group.
resource_client = ResourceManagementClient(credential, subscription_id)

rg_result = resource_client.resource_groups.create_or_update(RESOURCE_GROUP_NAME,
    { "___location": LOCATION })

print(f"Provisioned resource group {rg_result.name}")

# For details on the previous code, see Example: Provision a resource group
# at https://docs.microsoft.com/azure/developer/python/azure-sdk-example-resource-group


# Step 2: Provision the storage account, starting with a management object.

storage_client = StorageManagementClient(credential, subscription_id)

STORAGE_ACCOUNT_NAME = os.environ["STORAGE_ACCOUNT_NAME"] 

# Check if the account name is available. Storage account names must be unique across
# Azure because they're used in URLs.
availability_result = storage_client.storage_accounts.check_name_availability(
    { "name": STORAGE_ACCOUNT_NAME }
)

if not availability_result.name_available:
    print(f"Storage name {STORAGE_ACCOUNT_NAME} is already in use. Try another name.")
    exit()

# The name is available, so provision the account
poller = storage_client.storage_accounts.begin_create(RESOURCE_GROUP_NAME, STORAGE_ACCOUNT_NAME,
    {
        "___location" : LOCATION,
        "kind": "StorageV2",
        "sku": {"name": "Standard_LRS"}
    }
)

# Long-running operations return a poller object; calling poller.result()
# waits for completion.
account_result = poller.result()
print(f"Provisioned storage account {account_result.name}")


# Step 3: Retrieve the account's primary access key and generate a connection string.
keys = storage_client.storage_accounts.list_keys(RESOURCE_GROUP_NAME, STORAGE_ACCOUNT_NAME)

print(f"Primary key for storage account: {keys.keys[0].value}")

conn_string = f"DefaultEndpointsProtocol=https;EndpointSuffix=core.windows.net;AccountName={STORAGE_ACCOUNT_NAME};AccountKey={keys.keys[0].value}"

# print(f"Connection string: {conn_string}")

# Step 4: Provision the blob container in the account (this call is synchronous)
CONTAINER_NAME = os.environ["CONTAINER_NAME"]
container = storage_client.blob_containers.create(RESOURCE_GROUP_NAME, STORAGE_ACCOUNT_NAME, CONTAINER_NAME, BlobContainer())

print(f"Provisioned blob container {container.name}")

代码中的身份验证

本文稍后会使用 Azure CLI 登录到 Azure,以执行示例代码。 如果帐户有足够的权限在 Azure 订阅中创建资源组和存储资源,则脚本应成功运行,而无需其他配置。

若要在生产环境中使用此代码,请通过设置环境变量来使用服务主体进行身份验证。 此方法支持安全、自动化的访问,而无需依赖于交互式登录。 有关详细指南,请参阅 如何使用 Azure 服务对 Python 应用进行身份验证

确保为服务主体分配了具有足够权限的角色来创建资源组和存储帐户。 例如,在订阅级别分配参与者角色可提供必要的访问权限。 若要了解有关角色分配的详细信息,请参阅 Azure 中基于角色的访问控制(RBAC)。

5.运行脚本

  1. 如果尚未登录,请使用 Azure CLI 登录到 Azure:

    az login
    

  2. 运行以下脚本:

    python provision_blob.py
    

    脚本需要一两分钟才能完成。

6:验证资源

  1. 打开 Azure 门户 ,验证是否已按预期创建资源组和存储帐户。 可能需要等待一分钟,然后选择“显示资源组中的 隐藏类型 ”。

    新资源组的 Azure 门户页,其中显示了存储帐户

  2. 选择存储帐户,然后在左侧菜单中选择 数据存储>容器 以验证是否显示“blob-container-01”:

    显示 Blob 容器的存储帐户的 Azure 门户页

  3. 若要尝试从应用程序代码使用这些资源,请继续学习 示例:使用 Azure 存储

有关使用 Azure 存储管理库的另一个示例,请参阅 “管理 Python 存储”示例

7:清理资源

如果您希望在应用程序代码中使用这些资源,请遵循文章 示例:使用 Azure 存储,并保留这些资源。 否则,如果不需要保留在此示例中创建的资源组和存储资源,请运行 az group delete 命令。

资源组不会在订阅中产生任何持续费用,但资源组中的资源(如存储帐户)可能会产生费用。 清理不经常使用的组是一种很好的做法。 --no-wait 参数允许命令立即返回,而不是等待作完成。

#!/bin/bash
az group delete -n $AZURE_RESOURCE_GROUP_NAME --no-wait

有关参考:等效的 Azure CLI 命令

以下 Azure CLI 命令完成与 Python 脚本相同的创建步骤:

#!/bin/bash
#!/bin/bash

# Set variables
export LOCATION=<Location> # Change to your preferred region
export AZURE_RESOURCE_GROUP_NAME=<ResourceGroupName> # Change to your preferred resource group name
export STORAGE_ACCOUNT_NAME=<StorageAccountName> # Change to your preferred storage account name
export CONTAINER_NAME=<ContainerName> # Change to your preferred container name

# Provision the resource group
echo "Creating resource group: $AZURE_RESOURCE_GROUP_NAME"
az group create \
    --___location "$LOCATION" \
    --name "$AZURE_RESOURCE_GROUP_NAME"

# Provision the storage account
az storage account create -g $AZURE_RESOURCE_GROUP_NAME -l $LOCATION -n $STORAGE ACCOUNT_NAME --kind StorageV2 --sku Standard_LRS

echo Storage account name is $STORAGE_ACCOUNT_NAME

# Retrieve the connection string
CONNECTION_STRING=$(az storage account show-connection-string -g $AZURE_RESOURCE_GROUP_NAME -n $STORAGE_ACCOUNT_NAME --query connectionString)

# Provision the blob container
az storage container create --name $CONTAINER_NAME --account-name $STORAGE_ACCOUNT_NAME --connection-string $CONNECTION_STRING

另请参阅