0

我正在使用 python 来访问工头 API,以收集有关工头知道的所有主机的一些事实。不幸的是,v1 foreman API 中没有get-all-hosts-facts(或类似的东西),所以我不得不遍历所有主机并获取信息。这样做让我遇到了一个烦人的问题。对给定主机的每次调用都会返回一个 JSON 对象,如下所示:

{
  "host1.com": {
    "apt_update_last_success": "1452187711", 
    "architecture": "amd64", 
    "augeasversion": "1.2.0", 
    "bios_release_date": "06/03/2015", 
    "bios_vendor": "Dell Inc."
   }
}

这完全没问题,当我附加下一个主机的信息时会出现问题。然后我得到一个看起来像这样的 json 文件:

{
  "host1.com": {
    "apt_update_last_success": "1452187711", 
    "architecture": "amd64", 
    "augeasversion": "1.2.0", 
    "bios_release_date": "06/03/2015", 
    "bios_vendor": "Dell Inc."
}
}{
"host2.com": {
    "apt_update_last_success": "1452703454", 
    "architecture": "amd64", 
    "augeasversion": "1.2.0", 
    "bios_release_date": "06/03/2015", 
    "bios_vendor": "Dell Inc."
   }
}

这是执行此操作的代码:

for i in hosts_data:
    log.info("Gathering host facts for host: {}".format(i['host']['name']))
    try:
        facts = requests.get(foreman_host+api+"hosts/{}/facts".format(i['host']['id']), auth=(username, password))
        if hosts.status_code != 200:
            log.error("Unable to connect to Foreman! Got retcode '{}' and error message '{}'"
            .format(hosts.status_code, hosts.text))
            sys.exit(1)
    except requests.exceptions.RequestException as e:
        log.error(e)
    facts_data = json.loads(facts.text)
    log.debug(facts_data)
    with open(results_file, 'a') as f:
        f.write(json.dumps(facts_data, sort_keys=True, indent=4))

这是我需要文件的样子:

{
"host1.com": {
    "apt_update_last_success": "1452187711",
    "architecture": "amd64",
    "augeasversion": "1.2.0",
    "bios_release_date": "06/03/2015",
    "bios_vendor": "Dell Inc."
},
"host2.com": {
    "apt_update_last_success": "1452703454",
    "architecture": "amd64",
    "augeasversion": "1.2.0",
    "bios_release_date": "06/03/2015",
    "bios_vendor": "Dell Inc."
  }
}
4

3 回答 3

4

最好将所有数据组合到一个字典中,然后一次将其全部写出,而不是每次都在循环中。

d = {}
for i in hosts_data:
    log.info("Gathering host facts for host: {}".format(i['host']['name']))
    try:
        facts = requests.get(foreman_host+api+"hosts/{}/facts".format(i['host']['id']), auth=(username, password))
        if hosts.status_code != 200:
            log.error("Unable to connect to Foreman! Got retcode '{}' and error message '{}'"
            .format(hosts.status_code, hosts.text))
            sys.exit(1)
    except requests.exceptions.RequestException as e:
        log.error(e)
    facts_data = json.loads(facts.text)
    log.debug(facts_data)
    d.update(facts_data)  #add to dict
# write everything at the end
with open(results_file, 'a') as f:
    f.write(json.dumps(d, sort_keys=True, indent=4))
于 2016-10-25T17:08:37.170 回答
1

不要在循环内写入 json,而是将数据插入到dict具有正确结构的 a 中。然后在循环完成时将该 dict 写入 json 。

这假设您的数据集适合内存。

于 2016-10-25T17:08:31.737 回答
0

为了安全/一致性,您需要加载旧数据,对其进行变异,然后将其写回。

将电流with和更改write为:

# If file guaranteed to exist, can use r+ and avoid initial seek
with open(results_file, 'a+') as f:
    f.seek(0)
    combined_facts = json.load(f)
    combined_facts.update(facts_data)
    f.seek(0)
    json.dump(combined_facts, f, sort_keys=True, indent=4)
    f.truncate()  # In case new JSON encoding smaller, e.g. due to replaced key

注意:如果可能,您希望使用pault 的答案来最小化不必要的 I/O,如果数据检索应该是零碎完成的,这就是您应该这样做的方式,并在每个项目可用时立即更新。

仅供参考,不安全的方法是基本上找到尾随花括号,将其删除,然后写出一个逗号,后跟新的 JSON(从它的 JSON 表示中删除前导花括号)。它的 I/O 密集度要低得多,但也不太安全,不会清除重复项,不会对主机进行排序,根本不会验证输入文件等等。所以不要这样做。

于 2016-10-25T17:11:17.327 回答