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

如何将多主机REST API输出合并到单个变量并输出所有符合条件数据

问题描述

我有一个可在不同主机上调用的API用于获取数据,但当前代码执行条件判断时仅保留最后一台主机的数据,而非所有主机的符合条件数据。

示例数据

host1 API返回结果:

{'records': [{'node': '2551a', 'name': 'Temp', 'units': 'C', 'value': 40}, {'node': '1a','name': 'Out Flow Temp', 'units': 'C', 'value': 52}, {'node': '255rtp-1b', 'name': 'CPU0 Temp Margin', 'units': 'C', 'value': 25}],'num_records': 3}

host2 API返回结果:

{'records': [{'node': '700f', 'name': 'Temp', 'units': 'C', 'value': 28}, {'node': '1a','name': 'Temp3', 'units': 'C', 'value': 30}, {'node': '700rtp-1b', 'name': 'Temp Margin', 'units': 'C', 'value': 25}],'num_records': 3}

当前代码

for cluster in clusters_list:
    api_endpoint = f"https://{host}/api/private/"  # 补全原代码缺失的引号

    try:
        response = requests.request(method='GET', url=api_endpoint, **kwargs)
        response.raise_for_status()
    except Exception as error:
        print("Failed with error: {}.".format(error))
        return

    if response:
        rc = response.status_code
        data = response.json()
    #new_records = [record for record in data['records'] if record['value'] > 25]
    new_records = [record for record in data['records'] if 'value' in record and record['value'] > 20]
    records_beyond = {'records': new_records, 'num_records': len(new_records)}
print("sorted records",records_beyond)

当前问题

代码执行后仅输出host2的筛选结果,丢失了host1的数据:

{'records': [{'node': '700f', 'name': 'Temp', 'units': 'C', 'value': 28}, {'node': '1a','name': 'Temp3', 'units': 'C', 'value': 30}, {'node': '700rtp-1b', 'name': 'Temp Margin', 'units': 'C', 'value': 25}],'num_records': 3}

需要修改代码以保存所有主机的符合条件数据并统一输出。


解决方案

问题根源在于每次循环都覆盖了records_beyond变量,没有累加所有主机的结果。只需在循环外初始化一个容器收集数据,循环内将单主机结果存入容器即可。

修改步骤

  1. 在循环前初始化一个列表,用于存储所有主机的筛选结果
  2. 循环内处理完单主机数据后,将结果添加到列表中(可选:给每条记录添加主机标识,方便溯源)
  3. 循环结束后,统一输出所有结果,或合并成一个结构化数据

修改后代码

# 初始化容器,保存所有主机的结果
all_host_results = []

for cluster in clusters_list:
    api_endpoint = f"https://{host}/api/private/"

    try:
        response = requests.request(method='GET', url=api_endpoint, **kwargs)
        response.raise_for_status()
    except Exception as error:
        print("Failed with error: {}.".format(error))
        # 用continue替代return,避免单主机失败导致整个程序终止
        continue

    data = response.json()
    # 筛选value>20的记录
    new_records = [record for record in data['records'] if 'value' in record and record['value'] > 20]
    
    # 可选:给每条记录添加当前主机标识,便于区分来源
    for record in new_records:
        record['host'] = host
    
    # 将当前主机的结果存入容器
    host_result = {
        'host': host,
        'records': new_records,
        'num_records': len(new_records)
    }
    all_host_results.append(host_result)

# 输出按主机分组的筛选结果
print("所有主机符合条件的记录:", all_host_results)

# 可选:合并所有记录为一个统一结构
combined_records = []
for result in all_host_results:
    combined_records.extend(result['records'])
combined_output = {
    'total_num_records': len(combined_records),
    'records': combined_records
}
print("合并后的所有记录:", combined_output)

关键修改说明

  • 用all_host_results列表存储每台主机的结果,避免变量被覆盖
  • 将return改为continue,单主机API调用失败时不终止整个程序,继续处理其他主机
  • 可选添加host字段到每条记录,方便后续溯源数据来源
  • 提供两种输出方式:按主机分组的结果,或合并所有记录的统一结果

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 01:59:52