【问题标题】:How to split array and use several requests.get in parallel with python?如何拆分数组并使用多个 requests.get 与 python 并行?
【发布时间】:2022-12-19 16:11:57
【问题描述】:

我原来的要求是:

def get_foo_by_bars(authorisation_token: str, bar_ids: list):
    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_ids 大小包含更多 80 个元素,所以我的 url 大小是更多 2048 个字符。我希望能够与例如 10 bar_id 并行启动多个请求,然后在 return 之前的末尾合并 x 响应。

【问题讨论】:

    标签: python


    【解决方案1】:

    要使用 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 函数返回。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-06-15
      • 2017-06-14
      • 2023-02-22
      • 2021-07-13
      • 1970-01-01
      • 2013-09-08
      • 1970-01-01
      • 2014-07-01
      相关资源
      最近更新 更多