多线程请求 Python3

For*_*his 4 multithreading python-multithreading python-3.x python-requests

我对这个主题进行了大量研究,但问题是无法弄清楚如何使用 python3 发送多线程发布请求

names = ["dfg","dddfg","qwed"]

for name in names :
    res = requests.post(url,data=name)
    res.text 

Run Code Online (Sandbox Code Playgroud)

在这里,我想发送所有这些名称,并且我想使用多线程来使其更快。

eus*_*iro 10

解决方案 1 -concurrent.futures.ThreadPoolExecutor定义线程数

使用自定义函数 ( request_post) 您几乎可以做任何事情。

import concurrent
import requests

def request_post(url, data):
    return requests.post(url, data=data)

with concurrent.futures.ThreadPoolExecutor() as executor: # optimally defined number of threads
    res = [executor.submit(request_post, url, data) for data in names]
    concurrent.futures.wait(res)
Run Code Online (Sandbox Code Playgroud)

res将是request.Response包裹在Future实例上的每个请求的列表。要访问request.Response你需要使用res[index].result()其中index的大小len(names)

Future 对象可以让您更好地控制收到的响应,例如它是否正确完成或者是否存在异常或超时等。更多关于这里

您不必承担与大量线程相关的问题的风险(解决方案 2)。


解决方案 2 -multiprocessing.dummy.Pool为每个请求生成一个线程

如果您请求的页面不多,或者响应时间很慢,这可能会很有用。

from multiprocessing.dummy import Pool as ThreadPool
import itertools
import requests

with ThreadPool(len(names)) as pool: # creates a Pool of 3 threads 
    res = pool.starmap(requests.post(itertools.repeat(url),names))
Run Code Online (Sandbox Code Playgroud)

pool.starmap- 用于将多个参数传递(映射)到一个函数(requests.post),该函数将被线程列表(ThreadPool)调用。它将request.Response为每个请求返回一个列表。

intertools.repeat(url) 需要使第一个参数重复创建相同数量的线程。

names是第二个参数,requests.post所以它不需要显式使用可选参数就可以工作data。它的 len 必须与正在创建的线程数相同。

如果您需要调用另一个参数(如可选参数),则此代码将不起作用