Python:并行运行多个网络请求

标签 python python-3.x

我是 Python 的新手,我有一个基本问题,但我很难在网上找到答案,因为很多在线示例似乎都引用了已弃用的 API,如果之前有人问过这个问题,我很抱歉。

我正在寻找一种方法来并行执行多个(相似的)网络请求,并在列表中检索结果。

我现在的同步版本是这样的:

urls = ['http://example1.org', 'http://example2.org', '...']

def getResult(urls):
  result = []
  for url in urls:
    result.append(get(url).json())
  return result

我正在寻找异步等效项(所有请求都是并行发出的,但我会等待所有请求完成,然后再返回全局结果)。

据我所知,我必须使用 async/await 和 aiohttp,但这些示例对于我正在寻找的简单任务来说似乎太复杂了。

谢谢

最佳答案

我将尝试解释实现您想要的目标的最简单方法。我确信有更多更清洁/更好的方法来做到这一点,但就在这里。

您可以使用 python“threading”库执行您想要的操作。您可以使用它为每个请求创建单独的线程,然后并发运行所有线程并获得答案。

由于您是 python 的新手,为了进一步简化事情,我使用一个名为 RESULTS 的全局列表来存储 get(url) 的结果,而不是从函数返回它们。

import threading

RESULTS=[] #List to store the results

#Request Single Url Result and store in global RESULTS
def getSingleResult(url):
    global RESULTS
    RESULTS.append( ( url, get(url).json()) )

#Your Original Function
def getResult(urls)
    ths=[]
    for url in urls:
        th=threading.Thread(target=getSingleResult, args=(url,)) #Create a Thread
        th.start() #Start it
        ths.append(th) #Add it to a thread list

    for th in ths:
        th.join() #Wait for all threads to finish

全局结果的使用是为了更容易而不是直接从线程收集结果。如果您想这样做,可以查看此答案 How to get the return value from a thread in python?

当然要注意一件事,python 中的多线程不提供真正的并行性,而是提供并发性,特别是如果您使用标准的 python 实现,因为所谓的 Global Interpreter Lock

但是对于您的用例,它仍会为您提供所需的速度。

关于Python:并行运行多个网络请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63912870/

相关文章:

python - 无法理解 os.walk 的目录导航

python - 如何在 Python 中找到一个元素在列表中的位置?

python - 如何部署 airbnb 知识提要

html - 使用 bs4 查找和删除 HTML5 data-* 属性

python - 在Python3中将unicode序列转换为字符串但允许字符串中的路径

python - 绘图中的对数色标

python - 使用 QFileSystemModel 扩展 QTreeView 中的项目

python - Django 测试中出现异常错误,错误地认为实例不存在

python - 除了 : and except Exception as e: 之间的区别

python-3.x - python-fortran集成: callback comparison between f2py and ctypes