如何基于多列表批量生成指定参数的API请求并输出到文件
问题描述
我有三个列表:
servers = ['DC1','DC2','DC3'] main_process = ['1.exe','2.exe','3.exe'] sub_process = ['s1','s2','s3']
同时有一个JSON格式的API请求模板,需要根据列表元素数量(此案例为3次)将模板输出到文件中,每次输出替换模板中对应位置的列表元素,最终生成多段符合要求的POST请求内容。优先选择Bash脚本实现,Python方案也可接受。
Bash脚本实现
通过索引循环遍历三个数组,结合字符串替换生成每个请求内容并写入文件:
#!/bin/bash # 定义三个列表 servers=("DC1" "DC2" "DC3") main_process=("1.exe" "2.exe" "3.exe") sub_process=("s1" "s2" "s3") # 定义API请求模板,使用占位符标记需要替换的位置 template='POST api/alerting/rule { "params":{ "aggType":"avg", "termSize":6, "thresholdComparator":">", "timeWindowSize":5, "timeWindowUnit":"m", "groupBy":"top", "threshold":[ 1000 ], "index":[ ".test-index" ], "timeField":"@timestamp", "aggField":"sheet.version", "SERVER":"{{SERVER}}", "MAIN_PROCESS":"{{MAIN_PROCESS}}", "SUB_PROCESS":"{{SUB_PROCESS}}" }, "consumer":"alerts", "rule_type_id":".index-threshold", "schedule":{ "interval":"1m" }, "notify_when":"onActionGroupChange", "name":"my alert" }' # 输出文件路径 output_file="api_requests.txt" # 清空输出文件 > "$output_file" # 循环遍历每个索引,替换模板并写入文件 for i in "${!servers[@]}"; do server="${servers[$i]}" main_proc="${main_process[$i]}" sub_proc="${sub_process[$i]}" # 替换占位符并追加到文件 echo "$template" | sed -e "s/{{SERVER}}/$server/g" -e "s/{{MAIN_PROCESS}}/$main_proc/g" -e "s/{{SUB_PROCESS}}/$sub_proc/g" >> "$output_file" # 每个请求之间添加空行分隔 echo "" >> "$output_file" done echo "请求内容已生成到 $output_file"
说明:
- 用
${!servers[@]}获取数组索引,确保三个数组的元素按位置一一对应 - 修正了原模板中的JSON格式问题(缺失的逗号、括号闭合),保证输出内容合法
- 通过
sed命令批量替换占位符,将生成的请求内容追加到目标文件
Python脚本实现
利用zip函数将三个列表的元素配对,结合字符串格式化生成请求内容:
servers = ['DC1', 'DC2', 'DC3'] main_process = ['1.exe', '2.exe', '3.exe'] sub_process = ['s1', 's2', 's3'] # 定义请求模板,用占位符标记替换位置 template = '''POST api/alerting/rule {{ "params":{{ "aggType":"avg", "termSize":6, "thresholdComparator":">", "timeWindowSize":5, "timeWindowUnit":"m", "groupBy":"top", "threshold":[ 1000 ], "index":[ ".test-index" ], "timeField":"@timestamp", "aggField":"sheet.version", "SERVER":"{server}", "MAIN_PROCESS":"{main_proc}", "SUB_PROCESS":"{sub_proc}" }}, "consumer":"alerts", "rule_type_id":".index-threshold", "schedule":{{ "interval":"1m" }}, "notify_when":"onActionGroupChange", "name":"my alert" }} ''' output_file = 'api_requests.txt' with open(output_file, 'w') as f: # 遍历配对后的元素组 for server, main_proc, sub_proc in zip(servers, main_process, sub_process): # 格式化生成单条请求内容 request_content = template.format(server=server, main_proc=main_proc, sub_proc=sub_proc) f.write(request_content) f.write('\n\n') print(f'请求内容已生成到 {output_file}')
说明:
zip函数将三个列表的对应元素打包成元组,确保循环时元素一一匹配- 模板中的
{{和}}用于保留JSON的大括号,避免被格式化语法解析 - 以写入模式打开文件,批量写入所有请求内容,自动处理文件关闭
内容的提问来源于stack exchange,提问作者m.v
相关产品推荐
相关产品推荐

