快速入门:使用 Azure 应用程序配置创建 Python 应用Quickstart: Create a Python app with Azure App Configuration

在本快速入门中,你将使用适用于 Python 的应用程序配置客户端库通过 Azure 应用程序配置来集中存储和管理应用程序设置。In this quickstart, you will use Azure App Configuration to centralize storage and management of application settings using the Azure App Configuration client library for Python.

先决条件Prerequisites

创建应用配置存储区Create an App Configuration store

  1. 若要创建新应用程序配置存储区,请登录 Azure 门户To create a new App Configuration store, sign in to the Azure portal. 在主页的左上角,选择“创建资源” 。In the upper-left corner of the home page, select Create a resource. 在“搜索市场”框中,输入“应用程序配置”并选择 Enter 。In the Search the Marketplace box, enter App Configuration and select Enter.

    搜索应用配置

  2. 在搜索结果中选择“应用程序配置”,然后选择“创建” 。Select App Configuration from the search results, and then select Create.

    选择“创建”

  3. 在“创建应用配置”窗格中,输入以下设置:On the Create App Configuration pane, enter the following settings:

    设置Setting 建议的值Suggested value 说明Description
    订阅Subscription 订阅Your subscription 选择要用来测试应用配置的 Azure 订阅。Select the Azure subscription that you want to use to test App Configuration. 如果帐户只有一个订阅,则会自动选择该订阅并且不显示“订阅”列表 。If your account has only one subscription, it's automatically selected and the Subscription list isn't displayed.
    资源组Resource group AppConfigTestResources AppConfigTestResources 为应用程序配置存储区资源选择或创建资源组。Select or create a resource group for your App Configuration store resource. 此组可用于组织多个资源,删除该资源组可以同时删除这些资源。This group is useful for organizing multiple resources that you might want to delete at the same time by deleting the resource group. 有关详细信息,请参阅使用资源组管理 Azure 资源For more information, see Use resource groups to manage your Azure resources.
    资源名称Resource name 全局唯一名称Globally unique name 输入要用于应用程序配置存储区资源的唯一资源名称。Enter a unique resource name to use for the App Configuration store resource. 该名称必须是包含 5 到 50 个字符的字符串,只能包含数字、字母和 - 字符。The name must be a string between 5 and 50 characters and contain only numbers, letters, and the - character. 该名称的开头或末尾不能是 - 字符。The name can't start or end with the - character.
    位置Location 中国东部 2China East 2 使用“位置”指定在其中托管应用配置存储区的地理位置 。Use Location to specify the geographic location in which your app configuration store is hosted. 为获得最佳性能,请在应用程序的其他组件所在的同一区域创建资源。For the best performance, create the resource in the same region as other components of your application.
    定价层Pricing tier 免费Free 选择所需的定价层。Select the desired pricing tier. 有关详细信息,请参阅应用配置定价页For more information, see the App Configuration pricing page.
  4. 选择“查看 + 创建”以验证自己的设置 。Select Review + create to validate your settings.

  5. 选择“创建”。Select Create. 部署可能需要几分钟。The deployment might take a few minutes.

  6. 部署完成后,导航到“应用程序配置”资源。After the deployment finishes, navigate to the App Configuration resource. 选择“设置” > “访问密钥”。Select Settings > Access keys. 记下只读主密钥连接字符串。Make a note of the primary read-only key connection string. 稍后将使用此连接字符串来配置应用程序,以与创建的应用程序配置存储区进行通信。You'll use this connection string later to configure your application to communicate with the App Configuration store that you created.

  1. 选择“配置资源管理器” > “创建” > “键-值”来添加以下键值对 :Select Configuration Explorer > Create > Key-value to add the following key-value pairs:

    密钥Key Value
    TestApp:Settings:MessageTestApp:Settings:Message Azure 应用配置的数据Data from Azure App Configuration

    暂时将“标签”和“内容类型”保留为空 。Leave Label and Content Type empty for now.

  2. 选择“应用”。Select Apply.

设置 Python 应用Setting up the Python app

  1. 在本教程中,你将为名为 app-configuration-quickstart 的项目创建一个新目录。In this tutorial, you'll create a new directory for the project named app-configuration-quickstart.

    mkdir app-configuration-quickstart
    
  2. 切换到新创建的 app-configuration-quickstart 目录。Switch to the newly created app-configuration-quickstart directory.

    cd app-configuration-quickstart
    
  3. 使用 pip install 命令安装 Azure 应用程序配置客户端库。Install the Azure App Configuration client library by using the pip install command.

    pip install azure-appconfiguration
    
  4. 在 app-configuration-quickstart 目录中,创建名为 app-configuration-quickstart.py 的新文件,并添加以下代码 :Create a new file called app-configuration-quickstart.py in the app-configuration-quickstart directory and add the following code:

    import os
    from azure.appconfiguration import AzureAppConfigurationClient, ConfigurationSetting
    
    try:
        print("Azure App Configuration - Python Quickstart")
        # Quickstart code goes here
    except Exception as ex:
        print('Exception:')
        print(ex)
    

备注

本快速入门中的代码片段将帮助你开始使用适用于 Python 的应用程序配置客户端库。The code snippets in this quickstart will help you get started with the App Configuration client library for Python. 对于应用程序,你还应考虑根据需要处理异常。For your application, you should also consider handling exceptions according to your needs. 若要详细了解异常处理,请参阅 Python SDK 文档To learn more about exception handling, please refer to our Python SDK documentation.

配置应用程序配置连接字符串Configure your App Configuration connection string

  1. 设置名为“AZURE_APP_CONFIG_CONNECTION_STRING”的环境变量,并将其设置为应用程序配置存储区的访问密钥。Set an environment variable named AZURE_APP_CONFIG_CONNECTION_STRING, and set it to the access key to your App Configuration store. 在命令行中运行以下命令:At the command line, run the following command:

    setx AZURE_APP_CONFIG_CONNECTION_STRING "connection-string-of-your-app-configuration-store"
    

    如果使用 Windows PowerShell,请运行以下命令:If you use Windows PowerShell, run the following command:

    $Env:AZURE_APP_CONFIG_CONNECTION_STRING = "connection-string-of-your-app-configuration-store"
    

    如果使用 macOS 或 Linux,则请运行以下命令:If you use macOS or Linux, run the following command:

    export AZURE_APP_CONFIG_CONNECTION_STRING='connection-string-of-your-app-configuration-store'
    
  2. 重启命令提示符以使更改生效。Restart the command prompt to allow the change to take effect. 输出环境变量的值以验证其设置是否正确。Print out the value of the environment variable to validate that it is set properly.

代码示例Code samples

本部分中的示例代码片段演示如何通过适用于 Python 的应用程序配置客户端库执行常见操作。The sample code snippets in this section show you how to perform common operations with the App Configuration client library for Python. 将这些代码片段添加到之前创建的 app-configuration-quickstart.py 文件中的 try 块。Add these code snippets to the try block in app-configuration-quickstart.py file you created earlier.

备注

应用程序配置客户端库将键-值对象称为 ConfigurationSettingThe App Configuration client library refers to a key-value object as ConfigurationSetting. 因此在本文中,应用程序配置存储区中的“键-值”将被称为为“配置设置” 。Therefore, in this article, the key-values in App Configuration store will be referred to as configuration settings.

连接到应用程序配置存储区Connect to an App Configuration store

以下代码片段使用环境变量中存储的连接字符串创建 AzureAppConfigurationClient 实例。The following code snippet creates an instance of AzureAppConfigurationClient using the connection string stored in your environment variables.

    connection_string = os.getenv('AZURE_APP_CONFIG_CONNECTION_STRING')
    app_config_client = AzureAppConfigurationClient.from_connection_string(connection_string)

获取配置设置Get a configuration setting

以下代码片段按 key 名称检索配置设置。The following code snippet retrieves a configuration setting by key name.

    retrieved_config_setting = app_config_client.get_configuration_setting(key='TestApp:Settings:Message')
    print("\nRetrieved configuration setting:")
    print("Key: " + retrieved_config_setting.key + ", Value: " + retrieved_config_setting.value)

添加配置设置Add a configuration setting

以下代码片段使用 keyvalue 字段创建 ConfigurationSetting 对象,并调用 add_configuration_setting 方法。The following code snippet creates a ConfigurationSetting object with key and value fields and invokes the add_configuration_setting method. 如果尝试添加存储区中已存在的配置设置,此方法将引发异常。This method will throw an exception if you try to add a configuration setting that already exists in your store. 如果要避免此异常,可以改为使用 set_configuration_setting 方法。If you want to avoid this exception, the set_configuration_setting method can be used instead.

    config_setting = ConfigurationSetting(
        key='TestApp:Settings:NewSetting',
        value='New setting value'
    )
    added_config_setting = app_config_client.add_configuration_setting(config_setting)
    print("\nAdded configuration setting:")
    print("Key: " + added_config_setting.key + ", Value: " + added_config_setting.value)

获取配置设置列表Get a list of configuration settings

以下代码片段将检索配置设置列表。The following code snippet retrieves a list of configuration settings. 可提供 key_filterlabel_filter 参数,分别基于 keylabel 筛选键-值。The key_filter and label_filter arguments can be provided to filter key-values based on key and label respectively. 有关筛选的详细信息,请参阅如何查询配置设置For more information on filtering, see how to query configuration settings.

    filtered_settings_list = app_config_client.list_configuration_settings(key_filter="TestApp*")
    print("\nRetrieved list of configuration settings:")
    for item in filtered_settings_list:
        print("Key: " + item.key + ", Value: " + item.value)

锁定配置设置Lock a configuration setting

应用程序配置中键-值的锁定状态由 ConfigurationSetting 对象的 read_only 属性表示。The lock status of a key-value in App Configuration is denoted by the read_only attribute of the ConfigurationSetting object. 如果 read_onlyTrue,则该设置为锁定状态。If read_only is True, the setting is locked. 可使用 read_only=True 参数调用 set_read_only 方法来锁定配置设置。The set_read_only method can be invoked with read_only=True argument to lock the configuration setting.

    locked_config_setting = app_config_client.set_read_only(added_config_setting, read_only=True)
    print("\nRead-only status for " + locked_config_setting.key + ": " + str(locked_config_setting.read_only))

解锁配置设置Unlock a configuration setting

如果 ConfigurationSettingread_only 属性为 False,则该设置已解锁。If the read_only attribute of a ConfigurationSetting is False, the setting is unlocked. 可使用 read_only=False 参数调用 set_read_only 方法来解锁配置设置。The set_read_only method can be invoked with read_only=False argument to unlock the configuration setting.

    unlocked_config_setting = app_config_client.set_read_only(locked_config_setting, read_only=False)
    print("\nRead-only status for " + unlocked_config_setting.key + ": " + str(unlocked_config_setting.read_only))

更新配置设置Update a configuration setting

set_configuration_setting 方法可用于更新现有设置或创建新的设置。The set_configuration_setting method can be used to update an existing setting or create a new setting. 以下代码片段可更改现有配置设置的值。The following code snippet changes the value of an existing configuration setting.

    added_config_setting.value = "Value has been updated!"
    updated_config_setting = app_config_client.set_configuration_setting(added_config_setting)
    print("\nUpdated configuration setting:")
    print("Key: " + updated_config_setting.key + ", Value: " + updated_config_setting.value)

删除配置设置Delete a configuration setting

以下代码片段按 key 名称删除配置设置。The following code snippet deletes a configuration setting by key name.

    deleted_config_setting = app_config_client.delete_configuration_setting(key="TestApp:Settings:NewSetting")
    print("\nDeleted configuration setting:")
    print("Key: " + deleted_config_setting.key + ", Value: " + deleted_config_setting.value)

运行应用Run the app

在本快速入门中,你创建了一个 Python 应用,它使用 Azure 应用程序配置客户端库来检索通过 Azure 门户创建的配置设置、添加新设置、检索现有设置列表、锁定和解锁设置、更新设置和最终删除设置。In this quickstart, you created a Python app that uses the Azure App Configuration client library to retrieve a configuration setting created through the Azure portal, add a new setting, retrieve a list of existing settings, lock and unlock a setting, update a setting, and finally delete a setting.

此时,app-configuration-quickstart.py 文件应具有以下代码:At this point, your app-configuration-quickstart.py file should have the following code:

import os
from azure.appconfiguration import AzureAppConfigurationClient, ConfigurationSetting

try:
    print("Azure App Configuration - Python Quickstart")
    # Quickstart code goes here

    connection_string = os.getenv('AZURE_APP_CONFIG_CONNECTION_STRING')
    app_config_client = AzureAppConfigurationClient.from_connection_string(connection_string)

    retrieved_config_setting = app_config_client.get_configuration_setting(key='TestApp:Settings:Message')
    print("\nRetrieved configuration setting:")
    print("Key: " + retrieved_config_setting.key + ", Value: " + retrieved_config_setting.value)

    config_setting = ConfigurationSetting(
        key='TestApp:Settings:NewSetting',
        value='New setting value'
    )
    added_config_setting = app_config_client.add_configuration_setting(config_setting)
    print("\nAdded configuration setting:")
    print("Key: " + added_config_setting.key + ", Value: " + added_config_setting.value)

    filtered_settings_list = app_config_client.list_configuration_settings(key_filter="TestApp*")
    print("\nRetrieved list of configuration settings:")
    for item in filtered_settings_list:
        print("Key: " + item.key + ", Value: " + item.value)

    locked_config_setting = app_config_client.set_read_only(added_config_setting, read_only=True)
    print("\nRead-only status for " + locked_config_setting.key + ": " + str(locked_config_setting.read_only))

    unlocked_config_setting = app_config_client.set_read_only(locked_config_setting, read_only=False)
    print("\nRead-only status for " + unlocked_config_setting.key + ": " + str(unlocked_config_setting.read_only))

    added_config_setting.value = "Value has been updated!"
    updated_config_setting = app_config_client.set_configuration_setting(added_config_setting)
    print("\nUpdated configuration setting:")
    print("Key: " + updated_config_setting.key + ", Value: " + updated_config_setting.value)

    deleted_config_setting = app_config_client.delete_configuration_setting(key="TestApp:Settings:NewSetting")
    print("\nDeleted configuration setting:")
    print("Key: " + deleted_config_setting.key + ", Value: " + deleted_config_setting.value)

except Exception as ex:
    print('Exception:')
    print(ex)

在控制台窗口中,导航到包含 app-configuration-quickstart.py 文件的目录,然后执行以下 python 命令来运行应用:In your console window, navigate to the directory containing the app-configuration-quickstart.py file and execute the following python command to run the app:

python app-configuration-quickstart.py

应该会看到以下输出:You should see the following output:

Azure App Configuration - Python Quickstart

Retrieved configuration setting:
Key: TestApp:Settings:Message, Value: Data from Azure App Configuration

Added configuration setting:
Key: TestApp:Settings:NewSetting, Value: New setting value

Retrieved list of configuration settings:
Key: TestApp:Settings:Message, Value: Data from Azure App Configuration
Key: TestApp:Settings:NewSetting, Value: New setting value

Read-only status for TestApp:Settings:NewSetting: True

Read-only status for TestApp:Settings:NewSetting: False

Updated configuration setting:
Key: TestApp:Settings:NewSetting, Value: Value has been updated!

Deleted configuration setting:
Key: TestApp:Settings:NewSetting, Value: Value has been updated!

清理资源Clean up resources

如果不想继续使用本文中创建的资源,请删除此处创建的资源组以避免产生费用。If you do not want to continue using the resources created in this article, delete the resource group you created here to avoid charges.

重要

删除资源组的操作不可逆。Deleting a resource group is irreversible. 将永久删除资源组以及其中的所有资源。The resource group and all the resources in it are permanently deleted. 请确保不要意外删除错误的资源组或资源。Make sure that you don't accidentally delete the wrong resource group or resources. 如果在包含要保留的其他资源的资源组中创建了本文的资源,请从相应的窗格中单独删除每个资源,而不是删除该资源组。If you created the resources for this article inside a resource group that contains other resources you want to keep, delete each resource individually from its respective pane instead of deleting the resource group.

  1. 登录到 Azure 门户,然后选择“资源组”。Sign in to the Azure portal, and select Resource groups.
  2. 在“按名称筛选”框中,输入资源组的名称。In the Filter by name box, enter the name of your resource group.
  3. 在结果列表中,选择资源组名称以查看概述。In the result list, select the resource group name to see an overview.
  4. 选择“删除资源组”。Select Delete resource group.
  5. 系统会要求确认是否删除资源组。You're asked to confirm the deletion of the resource group. 重新键入资源组的名称进行确认,然后选择“删除” 。Enter the name of your resource group to confirm, and select Delete.

片刻之后,将会删除该资源组及其所有资源。After a few moments, the resource group and all its resources are deleted.

后续步骤Next steps

在本快速入门中,你创建了新的应用程序配置存储区,并了解到如何从 Python 应用访问键-值。In this quickstart, you created a new App Configuration store and learnt how to access key-values from a Python app.

有关其他代码示例,请访问:For additional code samples, visit: