Azure 应用配置 Python SDK(azure-appconfiguration-py)用于对 Azure App Configuration 进行集中式配置管理,支持功能标志与动态设置。
用途
该 SDK 面向需要集中管理应用配置的场景,可用于读取、写入和删除配置项,管理功能标志,创建配置快照,并对配置项进行只读锁定。它适用于将配置与应用代码分离、按环境(如 dev、staging、prod)区分配置值,以及通过功能标志实现渐进式发布和 A/B 测试。
安装与环境变量
安装命令:
pip install azure-appconfiguration
环境变量(连接字符串方式):
AZURE_APPCONFIGURATION_CONNECTION_STRING=Endpoint=https://<name>.azconfig.io;Id=...;Secret=...
或使用 Entra ID 时的端点:
AZURE_APPCONFIGURATION_ENDPOINT=https://<name>.azconfig.io
身份验证
连接字符串方式:
from azure.appconfiguration import AzureAppConfigurationClient
client = AzureAppConfigurationClient.from_connection_string(
os.environ["AZURE_APPCONFIGURATION_CONNECTION_STRING"]
)
Entra ID 方式:
from azure.appconfiguration import AzureAppConfigurationClient
from azure.identity import DefaultAzureCredential
client = AzureAppConfigurationClient(
base_url=os.environ["AZURE_APPCONFIGURATION_ENDPOINT"],
credential=DefaultAzureCredential()
)
主要能力
配置项管理:可通过 get_configuration_setting 获取单个配置项,支持按标签(label)获取环境特定值;使用 ConfigurationSetting 创建或更新配置项,可设置 key、value、label、content_type 和 tags;delete_configuration_setting 删除配置项;list_configuration_settings 支持按键前缀(key_filter)或标签(label_filter)过滤列出。
功能标志:功能标志以键前缀 .appconfig.featureflag/ 存储,值为包含 id、enabled、conditions 等字段的 JSON,content_type 为 application/vnd.microsoft.appconfig.ff+json;charset=utf-8。可通过 get_configuration_setting 读取,通过 list_configuration_settings 配合 key_filter ".appconfig.featureflag/*" 列出。
只读设置:通过 set_read_only(configuration_setting=setting, read_only=True) 将配置项锁定为只读,read_only=False 解除锁定。
快照:使用 ConfigurationSnapshot 与 ConfigurationSettingFilter 定义过滤条件,通过 begin_create_snapshot(...).result() 创建时间点快照,并可用 list_configuration_settings(snapshot_name="...") 列出快照内的配置项。
异步客户端:从 azure.appconfiguration.aio 与 azure.identity.aio 导入异步客户端与凭据,支持 await 方式获取配置,并在结束时关闭客户端与凭据。
客户端操作概览:
- get_configuration_setting:获取单个配置项
- set_configuration_setting:创建或更新配置项
- delete_configuration_setting:删除配置项
- list_configuration_settings:带过滤条件列出
- set_read_only:锁定/解锁配置项
- begin_create_snapshot:创建时间点快照
- list_snapshots:列出所有快照
使用方式与最佳实践
文档给出的实践建议包括:使用标签进行环境隔离(dev、staging、prod);使用键前缀进行逻辑分组(如 app:database:、app:cache:);将生产配置设为只读以防误改;在部署前创建快照以支持回滚;生产环境使用 Entra ID 而非连接字符串;在长时间运行的应用中定期刷新设置;使用功能标志进行渐进式发布与 A/B 测试。
适用场景与限制
适用场景为需要通过 Azure App Configuration 集中管理配置、功能标志和动态设置的任务。文档提示:仅当任务明确匹配上述范围时使用;不要把输出作为针对特定环境验证、测试或专家审查的替代;如果缺少必要输入、权限、安全边界或成功标准,应停止并请求澄清。文档未提供有关收费、价格、具体性能或效果的信息。