python实现并发http_python 2.7 如何实现http post多并发?
注意是python 2.7, (multiprocessing值支持到2.6,2.7下安裝會報(bào)錯(cuò))
用threadpool試了一下,總是報(bào)錯(cuò):
單次并發(fā)的函數(shù)
data = ['a', 'b', 'c']
#data傳到threadpool.makeRequests里面的第二個(gè)參數(shù),函數(shù)會將這個(gè)列表里面的值取出來,然后根據(jù)并發(fā)數(shù)進(jìn)行并發(fā)。
def repost(data):
response = requests.post(url, data).text
return response
結(jié)果處理函數(shù),只是打印出來
def postresult(requestself, responseresult):
print(responseresult)
#其他的處理,比如對結(jié)果插入到數(shù)據(jù)庫,或者寫入日志等,可以在這里寫
pool = threadpool.ThreadPool(5)
requests = threadpool.makeRequests(repost, data, postresult)
**#之前出問題,是因?yàn)檫@里requests的名稱定義和requests()方法沖突了。。。然后報(bào)錯(cuò)又很奇怪,沒引起注意,把這里的requests改個(gè)名字就OK了。各位,承讓了。
當(dāng)然,下面這一樣,也改一下。requests的名稱。
[pool.putRequest(req) for req in requests]
pool.wait()
報(bào)錯(cuò)如下:
Traceback (most recent call last):
File "C:\User\AppData\Local\Programs\Python\Python35-32\lib\site-packages\threadpool.py", line 158, in run
result = request.callable(*request.args, **request.kwds)
File "C:\test.py", line 29, in repost
response = requests.post(url, data1).text
AttributeError: 'list' object has no attribute 'post'
或者有沒有其他實(shí)現(xiàn)方法?
我靠,我靠,我靠靠靠。。。。問題解決了。看上面的備注。再見。
先把test.py全貼上來,看錯(cuò)誤提示你應(yīng)該是覆蓋了request變量,導(dǎo)致request變成了list類型。
建議,不要使用ThreadPool實(shí)現(xiàn)多并發(fā),基于Python的特性,即使你使用多線程,也只能同時(shí)運(yùn)行一條指令而已,多線程性能提升有限。
你首先應(yīng)該使網(wǎng)絡(luò)異步,然后實(shí)現(xiàn)基本的ioloop,也可以基于asyncio或tornado 實(shí)現(xiàn)單線程多并發(fā)
2.7沒有asyncio,你可以用gevent之類的,還有幾十2.7應(yīng)該是有multiprocessing的,只是你這種是io密集型的,用多進(jìn)程會適得其反, 用第三方庫實(shí)現(xiàn)協(xié)程吧
總結(jié)
以上是生活随笔為你收集整理的python实现并发http_python 2.7 如何实现http post多并发?的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 如何在ubuntu下安装detectro
- 下一篇: python科学计算三剑客_《Pytho