解决方法1:使用异步/并发方式调用API
import asyncio
import aiohttp
async def call_api(url):
async with aiohttp.ClientSession() as session:
async with session.get(url) as response:
return await response.text()
async def main():
api_urls = ['url1', 'url2', 'url3'] # 按顺序存放需要调用的API的URL
tasks = []
for url in api_urls:
tasks.append(call_api(url))
responses = await asyncio.gather(*tasks)
for response in responses:
if response is not None:
print(response)
break
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
解决方法2:使用多线程调用API
import threading
import requests
def call_api(url):
response = requests.get(url)
return response.text
def main():
api_urls = ['url1', 'url2', 'url3'] # 按顺序存放需要调用的API的URL
responses = []
threads = []
for url in api_urls:
thread = threading.Thread(target=lambda: responses.append(call_api(url)))
thread.start()
threads.append(thread)
for thread in threads:
thread.join()
for response in responses:
if response is not None:
print(response)
break
main()
这两种方法都是按顺序调用API,将每个API的调用放在一个独立的函数中,通过异步/并发或多线程的方式进行调用,最后判断每个API的响应,如果不为空则打印响应内容并结束程序。
上一篇:按顺序的散点图
下一篇:按顺序调用API,直到响应为空。