Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
241 views
in Technique[技术] by (71.8m points)

python 2.7 如何实现http post多并发?

注意是python 2.7, (multiprocessing值支持到2.6,2.7下安装会报错)

用threadpool试了一下,总是报错:

单次并发的函数

data = ['a', 'b', 'c']
#data传到threadpool.makeRequests里面的第二个参数,函数会将这个列表里面的值取出来,然后根据并发数进行并发。
def repost(data):
    response = requests.post(url, data).text
    return response

结果处理函数,只是打印出来

def postresult(requestself, responseresult):
    print(responseresult)
    #其他的处理,比如对结果插入到数据库,或者写入日志等,可以在这里写

pool = threadpool.ThreadPool(5)
requests = threadpool.makeRequests(repost, data, postresult)
**#之前出问题,是因为这里requests的名称定义和requests()方法冲突了。。。然后报错又很奇怪,没引起注意,把这里的requests改个名字就OK了。各位,承让了。
当然,下面这一样,也改一下。requests的名称。
[pool.putRequest(req) for req in requests]
pool.wait()

报错如下:

Traceback (most recent call last):
  File "C:UserAppDataLocalProgramsPythonPython35-32libsite-packageshreadpool.py", line 158, in run
    result = request.callable(*request.args, **request.kwds)
  File "C:est.py", line 29, in repost
    response = requests.post(url, data1).text
AttributeError: 'list' object has no attribute 'post'

或者有没有其他实现方法?

我靠,我靠,我靠靠靠。。。。问题解决了。看上面的备注。再见。


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

先把test.py全贴上来,看错误提示你应该是覆盖了request变量,导致request变成了list类型。

建议,不要使用ThreadPool实现多并发,基于Python的特性,即使你使用多线程,也只能同时运行一条指令而已,多线程性能提升有限。

你首先应该使网络异步,然后实现基本的ioloop,也可以基于asyncio或tornado 实现单线程多并发


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...