多线程请求Python3 [英] Multi Thread Requests Python3

查看:16
本文介绍了多线程请求Python3的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在这个问题上研究了很多,但问题是无法弄清楚如何使用python3发送多线程POST请求

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

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

在这里我想发送所有这些名字,并且我想使用多线程来提高速度。

推荐答案

解决方案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)

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

未来对象使您可以更好地控制收到的响应,例如它是否正确完成、是否存在异常或超时等。有关here

的详细信息

您不会冒与high number of threads(解决方案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))

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

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

namesrequests.post的第二个参数,因此它将在不需要显式使用可选参数data的情况下工作。其长度必须与正在创建的线程数相同。

如果需要调用另一个参数(如可选参数),此代码将无法运行

这篇关于多线程请求Python3的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆