簡體   English   中英

Python SDK Azure 資源圖響應不可迭代

[英]Python SDK Azure Resource Graph response not iterable

I'm trying to query resources in Azure subscriptions using the Azure Resource Graph python SDK from within an Azure Function. 它使用 Functions 運行時的事實並不重要,代碼也不能在本地運行。 查詢本身運行良好。 但是,我想在后續步驟中使用結果,這就是我遇到問題的地方。

    credentials, *_ = get_azure_cli_credentials()

    subscription_client = SubscriptionClient(credentials)
    subs = [sub.as_dict() for sub in subscription_client.subscriptions.list()]
    subs_list = []
    for sub in subs:
        subs_list.append(sub.get('subscription_id'))

    client = rg.ResourceGraphClient(credentials)

    request = QueryRequest(subscriptions=subs_list, query="resources | where type == 'microsoft.storage/storageaccounts'| where properties.supportsHttpsTrafficOnly == 'false'")

    response = client.resources(request)
    logging.info(response)

我嘗試了以下方法:

for resource in response:
    logging.info(resource)

這失敗了Exception: TypeError: 'QueryResponse' object is not iterable 供參考: https://docs.microsoft.com/en-us/python/api/azure-mgmt-resourcegraph/azure.mgmt.resourcegraph.models.queryresponse?view=azure-python

logging.info(response['data'])

這失敗了Exception: TypeError: 'QueryResponse' object is not subscriptable 現在有人知道如何使用此響應嗎? 謝謝!

結果類型QueryResponse具有可用於訪問結果數據的屬性data 由於QueryResponse不是字典,而是 class,因此您無法使用下標(方括號)訪問 data 屬性。 相反,您需要將其作為 class 的屬性來訪問,例如response.data

data屬性是一個帶有兩個鍵的字典, columns是返回的所有列的列表以及每列包含的數據類型, rows是結果中與查詢匹配的所有行的列表。

所以你的循環可能看起來像:

for resource in response.data['rows']:
    logging.info(resource)

通過傳遞QueryRequestOptions

client = ResourceGraphClient(credentials)

options = QueryRequestOptions(
    result_format=ResultFormat.object_array
)

request = QueryRequest(subscriptions=subs_list, query="<query>", options=options)

response = client.resources(request)

for resource in response.data:
    logging.info(resource)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM