Python 配置提供者

Python 包

Azure 应用程序配置是一项托管服务,可帮助开发人员简单安全地集中其应用程序配置。 Python 配置提供程序库允许以托管方式从Azure 应用程序配置存储加载配置。 此客户端库在适用于 Python 的 Azure SDK 的基础上添加了其他 功能性

安装软件包

使用 pip 安装 Azure 应用程序配置 提供程序包:

pip install azure-appconfiguration-provider

若要使用Microsoft Entra ID,还需要Azure标识。

pip install azure-identity

加载配置

load 包中的 azure-appconfiguration-provider 函数用于从 Azure 应用程序配置 加载配置。 load 函数允许使用 Microsoft Entra ID(建议)或连接字符串连接到 App Configuration 存储区。

注释

azure-appconfiguration-provider具有同步from azure.appconfiguration.provider import load和异步 from azure.appconfiguration.provider.aio import load 版本。 使用异步版本时,需要使用异步凭据from azure.identity.aio import DefaultAzureCredential

使用 DefaultAzureCredential 对应用配置存储进行身份验证。 按照说明为凭据分配应用程序配置数据读取者角色。

from azure.appconfiguration.provider import load
from azure.identity import DefaultAzureCredential

endpoint = "your-endpoint"
credential = DefaultAzureCredential()

# Connect to Azure App Configuration using a token credential and load all key-values with no label.
config = load(endpoint=endpoint, credential=credential)
print(config["message"]) # value of the key "message" from the App Configuration store

load 函数返回AzureAppConfigurationProvider的实例,该实例类似于字典的对象,包含从App Configuration存储加载的所有配置值。 默认情况下,提供程序从存储中加载所有未带标签的配置值。

JSON 内容类型处理

可以在App Configuration中创建 JSON 键值。 从Azure 应用程序配置加载键值时,配置提供程序会自动将有效 JSON 内容类型(例如 application/json)的键值转换为反序列化的 Python 对象。

{
    "key": "font",
    "label": null,
    "value": "{\r\n\t\"size\": 12,\r\n\t\"color\": \"red\"\r\n}",
    "content_type": "application/json"
}

此 JSON 内容会导致键值被加载为 { size: 12, color: "red" }

appConfig = load(endpoint, credential)
size = appConfig["font"]["size"]
color = appConfig["font"]["color"]

注释

从版本 2.2.0azure-appconfiguration-provider 开始,配置提供程序允许在具有 内容类型的键值中使用 application/json 中定义的注释。

使用选择器加载特定键值

默认情况下,load 方法从配置存储中加载所有没有标签的配置。 可以通过load的可选参数配置selects方法的行为,该参数是一个SettingSelector的列表。

from azure.appconfiguration.provider import load, SettingSelector
from azure.identity import DefaultAzureCredential

selects = [
    SettingSelector(key_filter="*", label_filter="\0"),  # Empty label
    SettingSelector(key_filter="*", label_filter="dev")  # 'dev' label
]
config = load(endpoint=endpoint, credential=DefaultAzureCredential(), selects=selects)

注释

键值会按选择器列出的顺序加载。 如果多个选择器检索具有相同键的键值,则最后一个选择器中的值将替代以前加载的任何值。

标签筛选器

标记筛选器参数选择具有特定标记的键值。 仅当键值包含筛选器中指定的所有标记和相应值时,才会加载键值。

from azure.appconfiguration.provider import load, SettingSelector
from azure.identity import DefaultAzureCredential
tag_filters = [{"env": "prod"}, {"region": "us"}]
selects = [SettingSelector(key_filter="*", label_filter="*", tag_filters=tag_filters)]
config = load(endpoint=endpoint, credential=DefaultAzureCredential(), selects=selects)

注释

星号 (*)、逗号 (,) 和反斜杠 (\) 字符是保留字符,在标记筛选器中使用时必须使用反斜杠进行转义。

从快照加载配置

可以使用中的snapshot_nameSettingSelector加载配置设置。 指定快照名称时,将加载该快照中的所有配置设置。 snapshot_name参数不能用于key_filterlabel_filtertag_filters

from azure.appconfiguration.provider import load, SettingSelector
from azure.identity import DefaultAzureCredential

snapshot_selects = [SettingSelector(snapshot_name="SnapshotName")]
config = load(endpoint=endpoint, credential=DefaultAzureCredential(), selects=snapshot_selects)

注释

如果使用版本 2.3.0 或更高版本的 azure-appconfiguration-provider 包,则可以使用快照支持。 只有使用组合类型 Key 创建的快照才能使用配置提供程序加载。

快照参考

快照引用是引用同一应用配置存储区中的快照的配置设置。 加载后,提供程序会解析它,并从该快照中添加所有键值。 使用快照引用可以在运行时在快照之间切换,这与添加快照选择器不同,这需要更改代码和/或重启才能切换到新快照。

有关创建快照引用的详细信息,请转到 快照参考概念

注释

若要使用快照引用,请使用包版本 2.4.0 或更高版本 azure-appconfiguration-provider

剪裁键

可以通过load参数向trim_prefixes函数提供一个要去除的键前缀列表来实现去除键前缀。

from azure.appconfiguration.provider import load
from azure.identity import DefaultAzureCredential

trim_prefixes = ["App1/"]
config = load(endpoint=endpoint, credential=DefaultAzureCredential(), trim_prefixes=trim_prefixes)
print(config["message"])  # Access the key "message" instead of "/application/message"

配置设置映射

configuration_mapper 参数允许你在处理配置设置并将其添加到提供程序之前对其进行转换。 映射器函数接收每个 ConfigurationSetting 对象,并且可以就地修改它。

from azure.appconfiguration.provider import load
from azure.identity import DefaultAzureCredential

def my_mapper(setting):
    if setting.key == "message":
        setting.value = "transformed value"

config = load(endpoint=endpoint, credential=DefaultAzureCredential(), configuration_mapper=my_mapper)

每当从存储加载配置设置时,都会调用映射器函数,从而使你能够:

  • 在添加值之前修改设置值
  • 转换或解密值
  • 根据设置键、标签或内容类型执行自定义处理

注释

在密钥修整被应用之前,映射器被调用。 检查映射器函数中的条件时,请使用原始键。

对于异步操作,请提供异步映射器函数:

from azure.appconfiguration.provider.aio import load
from azure.identity.aio import DefaultAzureCredential

async def my_async_mapper(setting):
    if setting.key == "secret_message":
        setting.value = await decrypt_value(setting.value)

config = await load(endpoint=endpoint, credential=DefaultAzureCredential(), configuration_mapper=my_async_mapper)

配置刷新

可以将提供程序配置为从应用配置存储中拉取最新设置,而无需重启应用程序。 若要刷新设置,请确保将refresh_enabled设置为True,并对由refresh方法返回的AzureAppConfigurationProvider实例调用load方法。

from azure.appconfiguration.provider import load
from azure.identity import DefaultAzureCredential

config = load(
    endpoint=endpoint,
    credential=DefaultAzureCredential(),
    refresh_enabled=True
)

# Later in your code, when application activity occurs
config.refresh()

默认情况下,使用刷新间隔为 30 秒,但可以使用参数替代它 refresh_interval 。 提供程序监视所有加载的键值以进行更改。

config = load(
    endpoint=endpoint,
    credential=DefaultAzureCredential(),
    refresh_enabled=True,
    refresh_interval=60
)

此设计可防止在应用程序空闲时向 App Configuration 发出不必要的请求。 应在发生应用程序活动时包含 refresh 调用。 此过程称为 活动驱动的配置刷新。 例如,可以在处理传入请求时或在执行复杂任务的迭代中调用 refresh

即使刷新调用因任何原因而失败,应用程序也会继续使用缓存的配置。 当配置的刷新间隔通过并且刷新调用由应用程序活动触发时,将进行另一次尝试。 在配置的刷新间隔过去之前调用 refresh 是一个空操作,因此,即使频繁调用,它的性能影响也很小。

自定义刷新回调

on_refresh_success仅当检测到更改且未发生错误时,才会调用该回调。 刷新 on_refresh_error 失败时调用回调。

from azure.appconfiguration.provider import load
from azure.identity import DefaultAzureCredential

def my_callback_on_success():
    # Do something on success
    pass

def my_callback_on_fail(error):
    # Do something on fail
    pass

config = load(
    endpoint=endpoint,
    credential=DefaultAzureCredential(),
    refresh_enabled=True,
    on_refresh_success=my_callback_on_success,
    on_refresh_error=my_callback_on_fail
)

更改特定密钥时刷新

可以使用 refresh_on 参数配置提供程序来监视特定监视密钥的更改,而不是监视所有加载的键值。 参数 refresh_on 是一个 List[WatchKey],它指定一个或多个需要监视其变化的键/标签。 在任何监视的键中检测到更改时,将刷新所有配置值。

from azure.appconfiguration.provider import load, WatchKey
from azure.identity import DefaultAzureCredential

config = load(
    endpoint=endpoint,
    credential=DefaultAzureCredential(),
    refresh_on=[WatchKey("Sentinel")]
)

注释

当设置 refresh_on 时,refresh_enabled 会自动默认为 True。 即使已配置 refresh_enabled,您也可以将 False 设置为 refresh_on 以禁用刷新。

功能标志

可以在Azure 应用程序配置中创建功能标志。 默认情况下,配置提供程序不会加载功能标志。 可以通过 feature_flag_enabled 参数启用加载和刷新特性标志。

config = load(endpoint=endpoint, credential=DefaultAzureCredential(), feature_flag_enabled=True)
alpha = config["feature_management"]["feature_flags"]["Alpha"]
print(alpha["enabled"])

默认情况下,当设置为 feature_flag_enabledTrue 时,将加载不带标签的所有功能标志。 如果要加载具有特定标签的功能标志,请使用 feature_flag_selectors 参数筛选功能标志。 此参数采用对象列表 SettingSelector

from azure.appconfiguration.provider import load, SettingSelector

config = load(
    endpoint=endpoint, 
    credential=DefaultAzureCredential(), 
    feature_flag_enabled=True, 
    feature_flag_selectors=[SettingSelector(key_filter="*", label_filter="dev")]
)
alpha = config["feature_management"]["feature_flags"]["Alpha"]
print(alpha["enabled"])

注释

若要有效地使用和管理从Azure 应用程序配置加载的功能标志,请安装和使用 featuremanagement 库。 此库提供了一种结构化方法来控制应用程序中的功能行为。

功能管理

功能管理库提供了一种基于功能标志开发和公开应用程序功能的方法。 功能管理库旨在与配置提供程序库协同工作。 配置提供程序将所有选定的功能标志加载到feature_flags 部分中的 feature_management 列表下的配置中。 功能管理库使用和管理应用程序的已加载功能标志。

以下示例演示如何将 featuremanagement 库与配置提供程序集成,以根据功能开关的状态动态控制 Express 应用程序中的 API 访问。

from azure.appconfiguration.provider import load
from featuremanagement import FeatureManager

config = load(endpoint=endpoint, credential=DefaultAzureCredential(), feature_flag_enabled=True)
feature_manager = FeatureManager(config)

print(f"Beta is: {feature_manager.is_enabled("Beta")}")

有关如何使用 Python 功能管理库的详细信息,请转到 功能标志快速入门

功能标志遥测

启用功能标志遥测时,Azure 应用程序配置提供程序向功能标志遥测数据注入其他属性。 这些属性提供有关功能标志及其评估的更多上下文:

  • AllocationID:表示功能标志分配状态的唯一标识符。
  • ETag:特性标志的当前 ETag。
  • FeatureFlagReference:对功能标志的引用,格式为 <AppConfigurationEndpoint>kv/<FeatureFlagKey>. 当存在标签时,引用将它作为查询参数包括: <AppConfigurationEndpoint>kv/<FeatureFlagKey>?label=<FeatureFlagLabel>

可以在 App Configuration 功能评估事件架构定义中找到完整的架构。 有关如何使用功能标志的遥测的详细信息,请转到 启用功能标志遥测演练

功能标志刷新

若要为功能标志启用刷新,需要设置 feature_flag_refresh_enabled=True。 此参数允许提供程序以与刷新配置相同的方式刷新功能标志。 与配置不同,所有加载的功能标志都会受到监视,以进行更改并导致刷新。 刷新配置设置和特性标志是相互独立的。 配置设置和功能标志均由 refresh 该方法更新,但功能标志更改不会导致配置刷新,反之亦然。 此外,如果未启用配置设置的刷新,仍可以启用功能标志进行刷新。

config = load(
    endpoint=endpoint, 
    credential=DefaultAzureCredential(), 
    feature_flag_enabled=True, 
    feature_flag_refresh_enabled=True
)

# Later in your code
config.refresh()

密钥保管库 参考

Azure 应用程序配置支持引用存储在Azure 密钥保管库中的机密。 在App Configuration中,可以创建映射到存储在密钥保管库中的机密的密钥。 机密被安全地存储在 密钥保管库 中,一旦加载后便可以像访问任何其他配置一样访问。

配置提供程序库会检索密钥保管库引用,就像它处理存储在App Configuration中的任何其他密钥一样。 由于客户端将密钥识别为 密钥保管库 引用,因此它们具有唯一的内容类型,客户端连接到 密钥保管库 以检索它们的值供应用程序使用。 需要通过提供凭据或提供客户端来配置连接到密钥保管库的方法。

使用凭据

可以使用凭据设置参数 keyvault_credential,并且所有密钥保管库引用都用它进行解析。 提供程序尝试使用所提供的凭据连接到任何引用的密钥保管库。

from azure.appconfiguration.provider import load, AzureAppConfigurationKeyVaultOptions
from azure.identity import DefaultAzureCredential

config = load(endpoint=endpoint, credential=DefaultAzureCredential(), keyvault_credential=DefaultAzureCredential())

与客户一起

可以使用客户端配置的字典设置参数 keyvault_client_configs

from azure.appconfiguration.provider import load
from azure.identity import DefaultAzureCredential

secret_clients = {
    key_vault_uri: {
        'credential': DefaultAzureCredential()
    }
}

config = load(endpoint=endpoint, credential=DefaultAzureCredential(), keyvault_client_configs=secret_clients)

注释

提供的任何额外属性都将传递到SecretClient 的创建过程。

机密解析器

如果未提供凭据或客户端,则可以使用私密解析器。 机密解析器提供了一种方法,可以将您期望的任何值返回到Key Vault引用。

from azure.appconfiguration.provider import load
from azure.identity import DefaultAzureCredential

def secret_resolver(uri):
    return "From Secret Resolver"

config = load(endpoint=endpoint, credential=DefaultAzureCredential(), secret_resolver=secret_resolver)

密钥保管库(密钥保管库)机密刷新

Azure 应用程序配置使你能够独立于配置刷新周期配置机密刷新间隔。 这对安全性至关重要,因为虽然 App Configuration 中的 密钥保管库 引用 URI 保持不变,但 密钥保管库 中的基础机密可能会作为你的安全措施之一进行轮换。

若要确保应用程序始终使用最新的机密值,请在其中secret_refresh_interval配置load关键字。 这强制提供程序在以下情况下从密钥保管库检索新的机密值:

  • 应用程序调用 refresh
  • 密钥设定的刷新间隔时间已过

即使在应用配置存储中未检测到任何更改,此机制仍能正常运行,确保您的应用程序与定期变更的机密保持同步。

from azure.appconfiguration.provider import load
from azure.identity import DefaultAzureCredential

config = load(
    endpoint=endpoint,
    credential=DefaultAzureCredential(),
    keyvault_credential=DefaultAzureCredential(),
    secret_refresh_interval=7200  # 2 hours
)

启动重试

配置加载是应用程序启动期间的关键路径操作。 为了确保可靠性,Azure 应用配置提供程序在初始配置加载期间实现可靠的重试机制。 这有助于保护应用程序免受暂时性网络问题的影响,否则可能会阻止成功启动。

可以通过设置startup_timeout参数来自定义此行为,该参数指定在启动时从Azure 应用程序配置加载数据所允许的时间(以秒为单位)。 默认值为 100 秒。

from azure.appconfiguration.provider import load
from azure.identity import DefaultAzureCredential

config = load(
    endpoint=endpoint,
    credential=DefaultAzureCredential(),
    startup_timeout=300
)

异地复制

Azure 应用程序配置提供程序库会自动发现提供的配置存储的副本,并在出现任何问题时使用副本。 有关详细信息,请参阅 异地复制

默认情况下启用副本发现。 如果要禁用它,可以设置为 replica_discovery_enabledFalse.

from azure.appconfiguration.provider import load
from azure.identity import DefaultAzureCredential

config = load(
    endpoint=endpoint, 
    credential=DefaultAzureCredential(), 
    replica_discovery_enabled=False
)

后续步骤

若要了解如何使用 Python 配置提供程序,请继续学习以下教程。

若要查看如何在 Web 应用程序中使用提供程序,请查看 Django 和 Flask 示例。