- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在尝试使用 Python 从 GCP Recommendations API 的 API JSON 输出中非法获取某些关键值,并且我对使用 Python 比较陌生。我试图非法获取的大多数值我都可以毫无问题地获取,但是,当我尝试在 JSON 中更深层嵌套的代码块中非法获取某些值时,它会失败并显示错误:TypeError: 'OperationGroup' object is not subscriptable
JSON 响应的完整输出在这里(某些值已更改以保护公司信息):
name: "projects/12345678910/locations/us-central1-a/recommenders/google.compute.instance.MachineTypeRecommender/recommendations/abcd-efg-hijk-lmnop-qrstuv-123456"
description: "Save cost by changing machine type from e2-medium to e2-small."
last_refresh_time {
seconds: 1623222401
}
primary_impact {
category: COST
cost_projection {
cost {
currency_code: "USD"
units: -12
nanos: -98539964
}
duration {
seconds: 2592000
}
}
}
content {
operation_groups {
operations {
action: "test"
resource_type: "compute.googleapis.com/Instance"
resource: "//compute.googleapis.com/projects/xyz/zones/us-central1-a/instances/abcname123"
path: "/machineType"
value_matcher {
matches_pattern: ".*zones/us-central1-a/machineTypes/e2-medium"
}
}
operations {
action: "replace"
resource_type: "compute.googleapis.com/Instance"
resource: "//compute.googleapis.com/projects/xyz/zones/us-central1-a/instances/abcname123"
path: "/machineType"
value {
string_value: "zones/us-central1-a/machineTypes/e2-small"
}
}
}
}
state_info {
state: ACTIVE
}
etag: "\"abc-123-def-456\""
recommender_subtype: "CHANGE_MACHINE_TYPE"
name: "projects/12345678910/locations/us-central1-a/recommenders/google.compute.instance.MachineTypeRecommender/recommendations/abcdefg-hijklmnop-123-456"
description: "Save cost by changing machine type from e2-medium to e2-small."
last_refresh_time {
seconds: 1623222401
}
primary_impact {
category: COST
cost_projection {
cost {
currency_code: "USD"
units: -12
nanos: -99648292
}
duration {
seconds: 2592000
}
}
}
content {
operation_groups {
operations {
action: "test"
resource_type: "compute.googleapis.com/Instance"
resource: "//compute.googleapis.com/projects/xyz/zones/us-central1-a/instances/instance-example1"
path: "/machineType"
value_matcher {
matches_pattern: ".*zones/us-central1-a/machineTypes/e2-medium"
}
}
operations {
action: "replace"
resource_type: "compute.googleapis.com/Instance"
resource: "//compute.googleapis.com/projects/xyz/zones/us-central1-a/instances/instance-example1"
path: "/machineType"
value {
string_value: "zones/us-central1-a/machineTypes/e2-small"
}
}
}
}
state_info {
state: ACTIVE
}
etag: "\"abcdefg12345\""
recommender_subtype: "CHANGE_MACHINE_TYPE"
name: "projects/12345678910/locations/us-central1-a/recommenders/google.compute.instance.MachineTypeRecommender/recommendations/abcd1234"
description: "Save cost by changing machine type from e2-medium to e2-small."
last_refresh_time {
seconds: 1623222401
}
primary_impact {
category: COST
cost_projection {
cost {
currency_code: "USD"
units: -11
nanos: -568971875
}
duration {
seconds: 2592000
}
}
}
content {
operation_groups {
operations {
action: "test"
resource_type: "compute.googleapis.com/Instance"
resource: "//compute.googleapis.com/projects/abcd/zones/us-central1-a/instances/instance-example2"
path: "/machineType"
value_matcher {
matches_pattern: ".*zones/us-central1-a/machineTypes/e2-medium"
}
}
operations {
action: "replace"
resource_type: "compute.googleapis.com/Instance"
resource: "//compute.googleapis.com/projects/abcd/zones/us-central1-a/instances/instance-example2"
path: "/machineType"
value {
string_value: "zones/us-central1-a/machineTypes/e2-small"
}
}
}
}
state_info {
state: ACTIVE
}
etag: "\"abcd1234\""
recommender_subtype: "CHANGE_MACHINE_TYPE"
这是我在 Python 中的代码:
from google.cloud import recommender
import os
client = recommender.RecommenderClient()
def main():
name = client.list_recommendations(parent='projects/xyzproject/locations/us-central1-a/recommenders/google.compute.instance.MachineTypeRecommender')
for element in name:
# print(element)
print(element.description)
print(element.primary_impact.category)
print(element.primary_impact.cost_projection.cost.currency_code)
print(element.primary_impact.cost_projection.cost.units)
print(element.state_info.state)
print(element.content.operation_groups)
for item in element.content.operation_groups:
print(item['resource_type'])
main()
上述工作的以下部分:
print(element.description)
print(element.primary_impact.category)
print(element.primary_impact.cost_projection.cost.currency_code)
print(element.primary_impact.cost_projection.cost.units)
print(element.state_info.state)
print(element.content.operation_groups)
但我遇到的错误和麻烦是:
for item in element.content.operation_groups:
print(item['resource_type'])
每当我尝试使用 python 脚本的那部分时,它都会失败并显示错误:
TypeError: 'OperationGroup' object is not subscriptable
那么,有人可以帮助我了解如何正确利用 JSON 响应并非法使用以下块中的信息(例如“resource_type”)?
content {
operation_groups {
operations {
action: "test"
resource_type: "compute.googleapis.com/Instance"
resource: "//compute.googleapis.com/projects/abcd/zones/us-central1-a/instances/instance-example2"
path: "/machineType"
value_matcher {
matches_pattern: ".*zones/us-central1-a/machineTypes/e2-medium"
}
}
operations {
action: "replace"
resource_type: "compute.googleapis.com/Instance"
resource: "//compute.googleapis.com/projects/abcd/zones/us-central1-a/instances/instance-example2"
path: "/machineType"
value {
string_value: "zones/us-central1-a/machineTypes/e2-small"
}
}
}
}
最佳答案
我采用了您问题中的代码并重新编写了它以匹配 Python Recommender API。主要问题是您正在访问内部成员和字段名称。我已更改代码以使用公共(public)接口(interface)。
查看 API 的类型定义:
Types for Recommender API Client
GitHub Gist: Python example demonstrating the Google Cloud Compute Recommender list recommendations api
# pip install google-cloud-recommender
from google.cloud import recommender
import os
# Enter values for your Project ID and Zone
PROJECT=
LOCATION=
RECOMMENDER = 'google.compute.instance.MachineTypeRecommender'
def print_recommendations():
client = recommender.RecommenderClient()
parent = client.recommender_path(PROJECT, LOCATION, RECOMMENDER)
recommendations = client.list_recommendations(parent=parent)
for recommendation in recommendations:
print('Recommendation:')
print(' Description: ', recommendation.description)
print(' Impact Category: ', recommendation.primary_impact.category)
print(' Currency Code: ', recommendation.primary_impact.cost_projection.cost.currency_code)
print(' Units: ', recommendation.primary_impact.cost_projection.cost.units)
print(' State: ', recommendation.state_info.state)
print('')
for op_group in recommendation.content._pb.operation_groups:
for operation in op_group.operations:
print(' Operation:')
print(' Action: ', operation.action)
print(' Resource Type: ', operation.resource_type)
print(' Path: ', operation.path)
print(' Value: ', operation.value.string_value)
print('')
print_recommendations()
示例输出:
Recommendation:
Description: Save cost by changing machine type from e2-standard-4 to e2-highmem-2.
Impact Category: Category.COST
Currency Code: USD
Units: -31
State: State.ACTIVE
Operation:
Action: test
Resource Type: compute.googleapis.com/Instance
Path: /machineType
Value:
Operation:
Action: replace
Resource Type: compute.googleapis.com/Instance
Path: /machineType
Value: zones/us-east1-b/machineTypes/e2-highmem-2
关于python-3.x - python : Fetching nested dictionary values GCP Recommendations,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67928039/
我正在用 Python (2.6) 编写一个应用程序,需要我使用字典作为数据存储。 我很好奇拥有一个大字典是否更节省内存,或者将其分解为许多(很多)较小的字典,然后拥有一个包含对所有较小字典的引用的“
Convert this [ "Cat" : ["A" : 1, "B": 2], "Mat" : ["C" : 3, "D": 4] ] Into [ "A" : 1,
有什么很酷的快速方法可以让两个字典创建第三个字典,以内连接方式将第一个字典的键映射到第二个字典的值? Dictionary dic1 = new Dictionary {{a1,b1},{a2,b2}
我希望将字典相互嵌套,以便容纳 block 的 xy 坐标。所以我会 IDictionary, IDictionary> 键 Dictionary 包含列、行组合,而值 Dictionary 包含 x
在 C# 中,我需要将数据保存在字典对象中,如下所示: Dictionary> MyDict = new Dictionary>(); 现在我意识到,在某些情况下我需要一些其他(不是字典类的)
第一个Dictionary就像 Dictionary ParentDict = new Dictionary(); ParentDict.Add("A_1", "1")
我似乎无法理解这个问题。我需要使用 LINQ 按内部字典的值对字典进行排序。有什么想法吗? 最佳答案 你的意思是你想要所有的值,按内部值排序? from outerPair in outer from
我想建模一个模式,其中响应是字典: { 'id1': { 'type': 'type1', 'active': true, }, 'id2': { 'type':
我有以下代码要添加或更新(如果已经存在)dict()-dict 中的值: if id not in self.steps: self.steps[ id ] = step else:
我有一个包含字典的 Swift 字典,我想使用存储的属性来访问键值: var json = [NSObject:AnyObject]() var title: String { get
我想创建一个 Dictionary>结构,我想提供一个 IEqualityComparer在包含 APerson 的second 字典中作为关键 如果我只有内部字典,那就是 var f = new D
我有一个集合,其中包含如下文档:文档 1: { "company": "ABC" "application": { "app-1": {"earning_from_src_A": 50,
我正在快速学习。 我发现 dictionary 就像 hash 用于 PHP 或其他一些语言。 那我怎么制作dictionary的dictionary呢?? 我有这样的数据 key:J name:jh
这个问题在这里已经有了答案: Explode a dict - Get all combinations of the values in a dictionary (2 个答案) 关闭 5 个月前
我是编程新手,所以如果我的问题看起来很愚蠢,我很抱歉。我想问一下有没有办法从 Multi.Dictionary 返回key当我有值(value)? 这是我的代码: Dim myDict Set myD
我试图找出标准 Ada 库是否配备了“字典”类型(我的意思是:一种以 格式存储值的数据结构,我可以从中检索 value 使用相应的唯一 key)。 这样的数据结构存在吗?如果是这样,有人可以提供一个
我究竟做错了什么?根据我的测试,objDic.exists 永远不会给出 False! dim objDic set objDic = createobject("scripting.
我想创建一个复合类型,其中包含一个字典作为其命名字段之一。但是明显的语法不起作用。我敢肯定有一些我不明白的基本原理。下面是一个例子: type myType x::Dict() end Jul
julia> hotcell2vocab = Dict([(cell, i-1+vocab_start) for (i,cell) in enumerate(h
我有一个简单的问题:我对 Dictionary.Value 集合进行了很多次迭代,这让我很烦,我必须调用 .ToList() 然后才能调用 .ForEach(),因为它似乎没有可枚举的Dictiona
我是一名优秀的程序员,十分优秀!