Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/facebook/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 3.x 多线程请求Python3_Python 3.x_Multithreading_Python Requests_Python Multithreading - Fatal编程技术网

Python 3.x 多线程请求Python3

Python 3.x 多线程请求Python3,python-3.x,multithreading,python-requests,python-multithreading,Python 3.x,Multithreading,Python Requests,Python Multithreading,我在这个主题上做了很多研究,但问题是我不知道如何使用python3发送多线程post请求 names = ["dfg","dddfg","qwed"] for name in names : res = requests.post(url,data=name) res.text 在这里,我想发送所有这些名称,并希望使用多线程来加快速度。解决方案1-定义线程数 使用自定义函数(request\u post)几乎可以做任何事情 import concurrent import

我在这个主题上做了很多研究,但问题是我不知道如何使用python3发送多线程post请求

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

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

在这里,我想发送所有这些名称,并希望使用多线程来加快速度。

解决方案1-定义线程数 使用自定义函数(
request\u 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
实例上的每个请求的列表。要访问
请求.响应
您需要使用
res[index].result()
其中
索引
大小为
len(names)

将来的对象可以让您更好地控制接收到的响应,比如它是否正确完成,是否存在异常或超时等。更多信息

您不承担与(解决方案2)相关的问题的风险


解决方案2-为每个请求生成一个线程 如果您请求的页面不多,或者响应时间很慢,则可能有用

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
-用于将多个参数传递(映射)到一个函数(
requests.post
),该函数将由线程列表(
ThreadPool
)调用。它将为每个请求返回一个列表

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

names
请求的第二个参数。post
因此无需显式使用可选参数
data
。其len必须与正在创建的线程数相同


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

对于python 3+1@bigbounty,最好使用asyncio和aiohttp。我怎么强调都不过分。实际上,你现在可以添加python不太了解的注释吗?这样我就可以稍微了解这段代码,而不是真正的部分在做什么。也许第二段代码可以工作,但我不知道如何在这里实现它,而我