要使用 Python 中的 requests 库并行发出多个请求,您可以使用 concurrent.futures 模块中的 ThreadPoolExecutor 类来创建线程池,然后使用 map 方法将一个函数并行应用于可迭代对象中的每个元素.
下面是一个示例,说明如何使用此方法将 bar_ids 列表拆分为大小为 10 的块,然后并行地为每个块发出单独的请求:
from concurrent.futures import ThreadPoolExecutor
def get_foo_by_bars(authorisation_token: str, bar_ids: list):
# Split the bar_ids list into chunks of size 10
bar_id_chunks = [bar_ids[i:i + 10] for i in range(0, len(bar_ids), 10)]
# Create a thread pool with as many threads as there are chunks
with ThreadPoolExecutor(max_workers=len(bar_id_chunks)) as executor:
# Use the map method to apply the send_request function to each chunk in parallel
results = executor.map(send_request, bar_id_chunks, [authorisation_token] * len(bar_id_chunks))
# Merge the results into a single list
merged_results = [item for sublist in results for item in sublist]
return merged_results
def send_request(bar_ids, authorisation_token):
r = requests.get(BASE_URL + "/api/v1/foo/bar",
params={"bar_ids": bar_ids, "data_type": "Float"},
headers={"Authorization": authorisation_token})
if r.status_code == 200:
return r.json()["data"]["data"]
这种方法将创建一个线程池,其中包含与 bar_id 块一样多的线程,然后使用这些线程并行发送请求。结果将被收集并合并到一个列表中,该列表将由 get_foo_by_bars 函数返回。