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

本文介绍如何使用 Python 脚本中的 Azure 管理库创建包含Azure 存储帐户和 Blob 存储容器的资源组。

创建资源后,请参阅示例:使用 Azure 存储 在 Python 应用程序代码中使用 Azure 客户端库将文件上传到 Blob 存储容器。

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

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

1:设置本地开发环境

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

2:安装所需的 Azure 库包

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

    azure-mgmt-resource
    azure-mgmt-storage
    azure-identity
    
  2. 在激活了虚拟环境的终端下,安装下列要求:

    pip install -r requirements.txt
    

3:编写代码以创建存储资源

创建包含以下代码的名为“provision_blob.py” 的 Python 文件。 注释提供了详细信息。 该脚本从环境变量 AZURE_SUBSCRIPTION_ID读取订阅 ID。 在后面的步骤中设置此变量。 资源组名称、位置、存储帐户名称和容器名称都定义为代码中的常量。

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

# Acquire a credential object.
credential = DefaultAzureCredential()

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

# Obtain the management object for resources.
resource_client = ResourceManagementClient(credential, subscription_id)

# Constants we need in multiple places: the resource group name and the region
# in which we provision resources. You can change these values however you want.
RESOURCE_GROUP_NAME = "PythonAzureExample-Storage-rg"
LOCATION = "centralus"

# Step 1: Provision the resource group.

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 = f"pythonazurestorage{random.randint(1,100000):05}"

# You can replace the storage account here with any unique name. A random number is used
# by default, but note that the name changes every time you run this script.
# The name must be 3-24 lower case letters and numbers only.


# 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 = "blob-container-01"
container = storage_client.blob_containers.create(RESOURCE_GROUP_NAME, STORAGE_ACCOUNT_NAME, CONTAINER_NAME, {})

# The fourth argument is a required BlobContainer object, but because we don't need any
# special values there, so we just pass empty JSON.

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

代码中的身份验证

本文稍后会使用 Azure CLI 登录到 Azure,以运行示例代码。 如果帐户有权在 Azure 订阅中创建资源组和存储资源,代码将成功运行。

若要在生产脚本中使用此类代码,可以将环境变量设置为使用基于服务主体的方法进行身份验证。 若要了解详细信息,请参阅 如何使用 Azure 服务对 Python 应用进行身份验证。 需要确保服务主体具有足够的权限,以便通过在 Azure 中为其分配适当的角色来创建资源组和存储资源;例如,订阅上的参与者角色。

4.运行脚本

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

    az login
    
  2. AZURE_SUBSCRIPTION_ID 环境变量设置为订阅 ID。 (可以运行 az account show 命令并从输出中的属性获取订阅 ID id ):

    set AZURE_SUBSCRIPTION_ID=00000000-0000-0000-0000-000000000000
    
  3. 运行以下脚本:

    python provision_blob.py
    

此脚本需要一到两分钟的时间才能完成。

5:验证资源

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

    Azure portal page for the new resource group, showing the storage account

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

    Azure portal page for the storage account showing the blob container

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

有关使用 Azure 存储管理库的其他示例,请参阅管理 Python 存储示例

有关参考:等效 Azure CLI 命令

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

rem Provision the resource group

az group create ^
-n PythonAzureExample-Storage-rg ^
-l centralus

rem Provision the storage account

set account=pythonazurestorage%random%
echo Storage account name is %account%

az storage account create ^
-g PythonAzureExample-Storage-rg ^
-l centralus ^
-n %account% ^
--kind StorageV2 ^
--sku Standard_LRS

rem Retrieve the connection string

FOR /F %i IN ('az storage account show-connection-string -g PythonAzureExample-Storage-rg -n %account% --query connectionString') do (SET connstr=%i)

rem Provision the blob container

az storage container create ^
--name blob-container-01 ^
--account-name %account% ^
--connection-string %connstr%

6:清理资源

如果要按照文章示例操作,请保留资源:使用Azure 存储在应用代码中使用这些资源。 否则,如果不需要保留在此示例中创建的资源组和存储资源,请运行 az group delete 命令。

资源组不会在订阅中产生任何持续费用,但资源组中的资源(如存储帐户)可能会产生费用。 最好清理未主动使用的任何组。 --no-wait 参数允许命令立即返回,而不是等到操作完成再返回。

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

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

另请参阅