背景:如果其中一个返回,并且score大于0.9,则无需等待其他响应。
为了实现一旦有一个请求返回并且score大于0.9就停止其他请求的功能,我们需要在多线程或多进程中加入一个机制来监听请求的结果。一旦找到满足条件的结果,就需要取消所有其他的请求任务。这里我们使用多线程来实现这一功能,因为取消任务在多线程环境中相对容易实现。
使用多线程实现
import requests
from concurrent.futures import ThreadPoolExecutor, as_completed, CancelledError
from pprint import pprint
# 定义请求的URL列表
urls = [
'http://example.com/api1',
'http://example.com/api2',
'http://example.com/api3',
# 更多URL...
]
def fetch_data(url):
""" 发送请求并返回数据 """
try:
response = requests.get(url, timeout=10)
response.raise_for_status() # 如果请求失败,抛出异常
return response.json()
except requests.exceptions.RequestException as e:
return {'error': f'Request failed for {url}: {str(e)}'}
def process_response(data):
""" 处理响应数据,确保包含'score'字段 """
if 'score' in data and data['score'] > 0.9:
return data
else:
return {'score': data.get('score', 0)}
def fetch_score(url):
""" 综合请求和处理逻辑 """
data = fetch_data(url)
return process_response(data)
def main():
stop_flag = False
stop_score = 0.9
def check_and_stop(future):
nonlocal stop_flag
try:
result = future.result()
if 'score' in result and result['score'] > stop_score:
stop_flag = True
print(f"Found a high score ({result['score']}) from {future._kwargs['args'][0]}, stopping other tasks.")
for fut in futures:
if fut != future and not fut.done():
fut.cancel()
except Exception as e:
print(f"Error processing future: {e}")
# 使用线程池执行异步请求
with ThreadPoolExecutor(max_workers=5) as executor:
futures = {executor.submit(fetch_score, url): url for url in urls}
# 监听所有任务的结果
for future in as_completed(futures):
if stop_flag:
break
check_and_stop(future)
# 收集所有完成的任务结果
results = []
for future in futures:
try:
results.append(future.result())
except CancelledError:
pass # 忽略被取消的任务
except Exception as e:
results.append({'error': f'Task failed: {str(e)}'})
# 输出结果
pprint(results)
if __name__ == '__main__':
main()
代码解释
1. 定义URL列表:urls列表包含了所有需要请求的API URL。
2. 定义请求函数:fetch_data函数用于向单个URL发送请求,并返回响应数据。
3. 定义处理函数:process_response函数用于处理响应数据,确保返回的字典中包含score字段,并检查是否大于0.9。
4. 定义综合请求和处理逻辑的函数:fetch_score函数调用fetch_data和process_response函数,完成整个请求和处理过程。
5. 主函数:
• 使用ThreadPoolExecutor创建一个执行器。
• 提交多个任务给执行器,每个任务对应一个URL的请求。
• 定义一个check_and_stop函数来检查每个任务的结果,如果score大于0.9,则设置stop_flag为True,并尝试取消其他未完成的任务。
• 使用as_completed函数来收集已完成的任务的结果,并在满足条件时停止其他任务。
• 将所有结果存储在一个列表中,并打印出来。
注意事项
• 取消任务:在Python的concurrent.futures模块中,CancelledError异常会被抛出,当任务被取消时。因此,我们捕获这个异常并忽略被取消的任务。
• 全局标志:使用stop_flag全局变量来标记是否已经找到了符合条件的结果。一旦找到,其他任务就会被取消。
• 任务监控:check_and_stop函数用于监控每个任务的结果,并在满足条件时采取行动。