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

使用Python每日获取Azure成本数据时遇AttributeError问题求助

解决Azure成本查询代码的AttributeError问题

问题原因

你的代码用了旧版Azure Cost Management SDK的API调用方式,新版SDK里Operations类已经移除了query属性,API结构做了调整,所以会抛出这个错误。

修复方案

1. 确保SDK是最新版

先升级依赖包:

pip install --upgrade azure-mgmt-costmanagement azure-identity

2. 修改代码适配新版API

新版SDK要求通过QueryDefinition构造查询参数,并用client.queries.execute执行查询,以下是修正后的完整代码:

from azure.mgmt.costmanagement import CostManagementClient
from azure.mgmt.costmanagement.models import QueryDefinition
from azure.identity import DefaultAzureCredential

# 初始化客户端(推荐用DefaultAzureCredential代替手动传credentials)
subscription_id = "你的订阅ID"
client = CostManagementClient(DefaultAzureCredential(), subscription_id)

# 定义时间范围(确保yesterday_start和yesterday_end是ISO格式字符串,比如'2024-05-20T00:00:00Z')
yesterday_start = "昨天开始时间"
yesterday_end = "昨天结束时间"

# 构造SQL风格的查询定义
query_def = QueryDefinition(
    query=f"SELECT sum(cost) as cost FROM cost where time >= '{yesterday_start}' and time <= '{yesterday_end}'"
)

# 执行查询,scope格式为"/subscriptions/你的订阅ID"
result = client.queries.execute(
    scope=f"/subscriptions/{subscription_id}",
    parameters=query_def
)

# 提取成本值(新版返回结构是properties.rows)
if result.properties.rows:
    cost = result.properties.rows[0][0]
    data.append({'subscription_id': subscription_id, 'cost': cost})
else:
    print("未查询到成本数据")

关键变更点

  • 旧版的client.operations.query.execute替换为client.queries.execute
  • 必须传入scope参数(格式为订阅/资源组等的完整路径)
  • 查询参数需要封装到QueryDefinition对象中
  • 结果提取从query_result.results改为result.properties.rows

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 04:18:21