Python的requests库,实现异步并发+控制间隔

方案一

使用

concurrent.futures.ThreadPoolExecutor

实现异步并发 + 控制间隔

import requests

import time

from concurrent.futures import ThreadPoolExecutor, as_completed

# 目标接口 URL(替换为你的实际接口)

URL = “https://api.example.com/data”

# 每次请求之间的间隔时间(单位:秒)

REQUEST_INTERVAL = 1 # 例如每秒发送一个请求

# 请求参数(可选)

PARAMS = {“param1”: “value1”}

# 并发请求数量

MAX_CONCURRENCY = 5 # 最大同时运行的线程数

# 存储请求结果

results = []

def fetch_data(url, params):

try:

# 发送请求并等待响应

response = requests.get(url, params=params)

response.raise_for_status() # 检查 HTTP 错误

return response.json() # 假设返回 JSON 数据

except Exception as e:

print(f”请求失败: {e}”)

return None

def main():

# 创建线程池

with ThreadPoolExecutor(max_workers=MAX_CONCURRENCY) as executor:

futures = []

for i in range(10): # 假设总共发送 10 个请求

# 提交任务到线程池

future = executor.submit(fetch_data, URL, PARAMS)

futures.append(future)

# 控制并发间隔:每次提交后等待固定时间

time.sleep(REQUEST_INTERVAL)

# 收集结果(按完成顺序)

for future in as_completed(futures):

result = future.result()

if result:

results.append(result)

print(f”获取到结果: {result}”)

print(“所有请求完成,共获取到 {} 个结果。”.format(len(results)))

if __name__ == “__main__”:

main()

© 版权声明

相关文章

暂无评论

none
暂无评论...