本文實(shí)例講述了Python實(shí)現(xiàn)可設(shè)置持續(xù)運(yùn)行時(shí)間、線程數(shù)及時(shí)間間隔的多線程異步post請(qǐng)求功能。分享給大家供大家參考,具體如下:
#coding=utf8'''random.randint(a, b):用于生成一個(gè)指定范圍內(nèi)的整數(shù)。其中參數(shù)a是下限,參數(shù)b是上限,生成的隨機(jī)數(shù)n: a <= n <= brandom.choice(sequence):從序列中獲取一個(gè)隨機(jī)元素參數(shù)sequence表示一個(gè)有序類型(列表,元組,字符串)'''import httplib,jsonimport timeimport threadingfrom random import randint,choice#創(chuàng)建請(qǐng)求函數(shù)def postRequest(threadNum): postJson={ } #定義需要進(jìn)行發(fā)送的數(shù)據(jù) postData=json.dumps(postJson) #定義一些文件頭 headerdata = { "content-type":"application/json", } #接口 requrl ="/v1/query" #請(qǐng)求服務(wù),例如:www.baidu.com hostServer="" #連接服務(wù)器 conn = httplib.HTTPConnection(hostServer) #發(fā)送請(qǐng)求 conn.request(method="POST",url=requrl,body=postData,headers=headerdata) #獲取請(qǐng)求響應(yīng) response=conn.getresponse() #打印請(qǐng)求狀態(tài) if response.status in range(200,300): print u"線程"+str(threadNum)+u"狀態(tài)碼:"+str(response.status) conn.close()def run(threadNum,internTime,duration): #創(chuàng)建數(shù)組存放線程 threads=[] try: #創(chuàng)建線程 for i in range(1,threadNum): #針對(duì)函數(shù)創(chuàng)建線程 t=threading.Thread(target=postRequest,args=(i,)) #把創(chuàng)建的線程加入線程組 threads.append(t) except Exception,e: print e try: #啟動(dòng)線程 for thread in threads: thread.setDaemon(True) thread.start() time.sleep(internTime) #等待所有線程結(jié)束 for thread in threads: thread.join(duration) except Exception,e: print eif __name__ == '__main__': startime=time.strftime("%Y%m%d%H%M%S") now=time.strftime("%Y%m%d%H%M%S") duratiion=raw_input(u"輸入持續(xù)運(yùn)行時(shí)間:") while (startime+str(duratiion))!=now: run(10,1,int(duratiion)) now=time.strftime("%Y%m%d%H%M%S")運(yùn)行結(jié)果:

更多關(guān)于Python相關(guān)內(nèi)容可查看本站專題:《Python Socket編程技巧總結(jié)》、《Python數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Python函數(shù)使用技巧總結(jié)》、《Python字符串操作技巧匯總》、《Python入門與進(jìn)階經(jīng)典教程》及《Python文件與目錄操作技巧匯總》
希望本文所述對(duì)大家Python程序設(shè)計(jì)有所幫助。
|
新聞熱點(diǎn)
疑難解答
圖片精選