查询分页api url列表的最快方法



我有一个api_urls:列表

api_urls = [api_url_1, api_url_2, api_url_3]

对于这些URL中的每一个,我都必须循环进行分页以获得所有数据:

def get_data(api_url):
next_page = 1
results = []
while next_page is not None:
response = query(api_url)
results.extend(response["data"])
next_page = response["next_page"]
return results

从我的所有api_urls中获取数据的最快方法是什么?我可以在这里执行多线程吗?

您可以使用Threadpool在4个不同的线程中并行运行get_data函数。

from multiprocessing.pool import ThreadPool
with ThreadPool(4) as pool:
results = pool.map(get_data, api_urls)

此代码使用4个线程并行执行get_data函数,直到所有api_urls都被处理为止

您还可以使用此代码在使用普通多处理池的4个并行进程上运行get_data函数

from multiprocessing import Pool
with Pool(4) as pool:
results = pool.map(test, api_urls)

最新更新