You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Python获取Azure Savings Plan利用率数据时遇属性错误

问题原因及修复方法

问题根源

  1. SDK版本过低:你使用的azure-mgmt-costmanagement Python SDK版本不包含benefit_utilization_summaries模块,该模块是Cost Management API较新版本才引入的功能。
  2. 代码缩进错误:原代码存在缩进混乱问题,Python对缩进敏感,会导致语法错误或逻辑执行异常。
  3. 客户端初始化不规范:未指定支持该API的版本号,可能导致客户端无法识别新的API端点。

修复步骤

1. 升级Cost Management SDK

执行以下命令将SDK升级到最新版本:

pip install --upgrade azure-mgmt-costmanagement

2. 修正代码缩进与客户端配置

使用以下修正后的代码,注意缩进规范,并显式指定支持benefit_utilization_summaries的API版本:

from azure.identity import ClientSecretCredential
from azure.mgmt.costmanagement import CostManagementClient

# 初始化服务主体凭据
credential = ClientSecretCredential(
    tenant_id='你的租户ID',
    client_id='你的客户端ID',
    client_secret='你的客户端密钥'
)

# 初始化CostManagementClient,指定支持目标API的版本
client = CostManagementClient(
    credential=credential,
    api_version="2022-10-01"  # 该版本及以上支持Benefit Utilization Summaries操作
)

# 调用API拉取计费账户下的储蓄计划利用率数据
response = client.benefit_utilization_summaries.list_by_billing_account_id(
    billing_account_id="你的计费账户ID"
)

# 遍历并打印结果
for item in response:
    print(item.as_dict())  # 转换为字典格式更易读

3. 权限验证

确保你的服务主体(对应客户端ID的身份)拥有Cost Management Reader或更高权限,否则会因权限不足无法获取数据。

内容的提问来源于stack exchange,提问作者learningtocode

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 04:05:21