拆分函数后Python while循环仅执行一次API请求问题
API循环请求拆分函数后仅执行一次的问题分析与修复
问题原因
- 提前终止循环:拆分后的
create_spirion_session函数在while True循环的第一次迭代中就执行了return(results),直接跳出函数并结束循环,导致仅执行一次API请求。而合并版函数没有提前return,循环会持续执行。 - 缺失分页更新逻辑:合并版隐含了用
newestTimestamp更新下一次请求参数的逻辑(用于获取后续数据),但拆分版中完全没有处理timestamp的更新,即使去掉return,也会重复请求同一批次数据,无法获取新数据。
修复方案
- 将
create_spirion_session改为生成器函数,用yield替代return,每次生成请求结果后继续循环,而非终止函数。 - 添加循环终止条件:当返回无数据或无新时间戳时,主动退出循环。
- 恢复分页参数更新逻辑:用每次结果中的
newestTimestamp更新下一次请求的timestamp参数,确保获取后续批次的数据。 - 在
main函数中遍历生成器,逐个处理每次请求的结果。
修改后的完整代码
from os import times from textwrap import indent from unittest import TestSuite from urllib import request from xxlimited import new import requests import ssl import json import csv ssl._create_default_https_context = ssl._create_unverified_context import urllib3 def create_spirion_session(): urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) url = 'https://SV03TMCSPAPP/WebApi/Services/Home/LogOn' url2 = 'https://SV03TMCSPAPP/WebApi/Services/Data/LoadEndpoints' headers = { 'Accept':'application/json, text/plain', 'Content-Type': 'application/json' } timestampfromSpirion = "timestamp_records.csv" results = [] results2 = [] f = open('spirion.json') timestampData = json.load(f) with requests.Session() as s: # 认证步骤 resp = s.post(url, json={"user": "","password": ""}, headers=headers, verify=False) print(f"认证状态码: {resp.status_code}") timestamp = "" deleteData = "" fields = "" while True: # 发送API请求 resp2 = s.post(url2, json={"deleteData": deleteData, "timestamp": timestamp, "fields": fields}, headers=headers, verify=False) resp3 = resp2.text.split('\n', 1)[1] results = json.loads(resp3) # 终止条件:无数据或无有效数据 if not results or not results.get('data'): break # 生成当前批次结果,供外部处理 yield results # 更新timestamp以获取下一批数据 if 'newestTimestamp' in results: timestamp = results['newestTimestamp'] else: # 无新时间戳,终止循环 break def parse_agg_results(results): if not results: return buckets = results.get('newestTimestamp', '无最新时间戳') print(f"最新时间戳: {buckets}") # 处理主机数据逻辑 for computer in results.get('data', []): host_name = computer.get('hostName', '未知主机') if 'lastSearchTime' in computer: print(f"{host_name} - 最后搜索时间: {computer['lastSearchTime']}") else: print(f"{host_name} - 无最后搜索时间记录") def main(): # 遍历生成器,处理每一次请求的结果 for results in create_spirion_session(): parse_agg_results(results) def entrypoint(): try: main() except KeyboardInterrupt: print("Keyboard interrupt. Exiting.", flush=True) print("", flush=True) if __name__ == "__main__": entrypoint()
内容的提问来源于stack exchange,提问作者dot_davidjb
相关产品推荐
相关产品推荐

