【问题标题】:Making multiple API calls in parallel using Python (IPython)使用 Python (IPython) 并行进行多个 API 调用
【发布时间】:2013-06-07 11:03:31
【问题描述】:

我正在本地机器 (Mac) 上使用 Python(IPython 和 Canopy)和 RESTful 内容 API。

我有一组 3000 个唯一 ID 可从 API 中提取数据,并且一次只能使用一个 ID 调用 API。

我希望以某种方式并行进行 3 组 1000 次调用以加快速度。

最好的方法是什么?

提前感谢您的帮助!

【问题讨论】:

  • 您是否考虑使用线程(每个请求的单独线程)?
  • 我可以接受,只要它是正确的选择 - 我想整个事件是“令人尴尬的可并行化”......

标签: python api parallel-processing


【解决方案1】:

如果没有关于您具体做什么的更多信息,很难确定,但简单的线程方法可能是有意义的。

假设您有一个处理单个 ID 的简单函数:

import requests

url_t = "http://localhost:8000/records/%i"

def process_id(id):
    """process a single ID"""
    # fetch the data
    r = requests.get(url_t % id)
    # parse the JSON reply
    data = r.json()
    # and update some data with PUT
    requests.put(url_t % id, data=data)
    return data

您可以将其扩展为一个处理一系列 ID 的简单函数:

def process_range(id_range, store=None):
    """process a number of ids, storing the results in a dict"""
    if store is None:
        store = {}
    for id in id_range:
        store[id] = process_id(id)
    return store

最后,您可以相当轻松地将子范围映射到线程上,以允许一定数量的请求并发:

from threading import Thread

def threaded_process_range(nthreads, id_range):
    """process the id range in a specified number of threads"""
    store = {}
    threads = []
    # create the threads
    for i in range(nthreads):
        ids = id_range[i::nthreads]
        t = Thread(target=process_range, args=(ids,store))
        threads.append(t)

    # start the threads
    [ t.start() for t in threads ]
    # wait for the threads to finish
    [ t.join() for t in threads ]
    return store

IPython Notebook 中的完整示例:http://nbviewer.ipython.org/5732094

如果您的单个任务需要更广泛的时间,您可能需要使用ThreadPool,它会一次分配一个任务(如果单个任务非常小,通常会更慢,但可以保证在异构任务中实现更好的平衡例)。

【讨论】:

  • 快速一个 :: 上面的作用是什么?为什么不只是一个:?
  • 表示大步。指定切片时,有三个数字:start:stop:stride。所以1::3 表示每隔三个元素,从 1 开始,即[1,4,7,...]。这只是对列表进行平均分区的一种简单方法。
  • 所以双冒号只是表示未指定停止,默认为“结束”。
  • @minrk - 如果我没有将 id 作为单独的参数及其 json 的一部分传递,我该怎么做?
猜你喜欢
  • 2019-11-16
  • 2022-09-23
  • 1970-01-01
  • 2019-03-10
  • 1970-01-01
  • 1970-01-01
  • 2021-10-07
  • 2023-04-10
  • 1970-01-01
相关资源
最近更新 更多