我正在编写一个导出监视数据的程序。

我有python代码,它发送API请求并以字典的形式作为json获得响应。

响应如下所示:

[
  {
    "diskwrite": 667719532544,
    "name": "test-hostname",
    "maxmem": 536870912,
    "diskread": 876677015576,
    "mem": 496111616,
    "id": "qemu/102",
    "node": "node1",
    "template": 0,
    "cpu": 0.00947819269772254,
    "vmid": 102,
    "type": "qemu",
    "maxcpu": 2,
    "netout": 15081562546,
    "maxdisk": 10737418240,
    **"status": "running",**
    "netin": 15852619497,
    "disk": 0,
    "uptime": 3273086
  },
  {
    "maxcpu": 8,
    "type": "qemu",
    "vmid": 106,
    "cpu": 0.500598230113925,
    "template": 0,
    "node": "node1",
    "id": "qemu/106",
    "mem": 10341007360,
    "maxmem": 10737418240,
    "diskread": 8586078094720,
    "name": "some.other-hostname",
    "diskwrite": 6052378838016,
    "uptime": 1900411,
    "disk": 0,
    "netin": 4899018841106,
    **"status": "stopping",**
    "maxdisk": 107374182400,
    "netout": 4788420573355
  },
  ...


我想按原样遍历所有主机名及其项(“ diskwrite”,“ mem”,“ cpu”等),但仅在它们处于运行状态时,我想将它们添加到字典中(“状态”:“正在运行”)。

ram_metric.set({'type': "total"}, ram[0])
cpu_metric.set({'type': 'average', 'interval': '5 minutes'}, cpu[0])


我还需要一个循环,使这一行代码生效,并为每个“名称”项使用host = name创建此行:

ram_metric = Gauge("memory_usage_bytes", "Memory usage in bytes.",
                       {'host': host})
cpu_metric = Gauge("cpu_usage_percent", "CPU usage percent.",
                       {'host': host})


拜托,我不知道该怎么做。

最佳答案

我可以帮忙。

您得到的响应是一个带有字典的列表,您只有在状态首先运行时才有兴趣:

def get_all_vm():
    all_vm = get_request("/api2/json/cluster/resources?type=vm")
    vm = all_vm['data']
    list = [item for item in vm if item['status'] == "running"]
    return list
metric = get_all_vm()


现在您可以遍历所有项,并且(1)通过item [“ newkey”] = newvalue添加新值,或者(2)使用dict迭代遍历现有键

for item in metric:
   item["justanexample"] = "test"
   for key,value in item.items():
       if key == "mem":
           ram_metric.set({'name': metric['data']['name'], 'type': 'usage'}, metric['data']['mem'])
       elif key == "cpu":
           cpu_metric.set({'name': metric['data']['name'], 'type': 'load'}, metric['data']['cpu'])
...

关于python - Python导出一些列表并全部放入for循环,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/44944256/

10-13 04:59