這篇文章主要介紹了Python實現可設置持續運行時間、線程數及時間間隔的多線程異步post請求功能,涉及Python網絡請求的創建、發送、響應、處理等相關操作技巧,需要的朋友可以參考下
本文實例講述了Python實現可設置持續運行時間、線程數及時間間隔的多線程異步post請求功能。分享給大家供大家參考,具體如下:
#coding=utf8
'''
random.randint(a, b):用於生成一個指定範圍內的整數。
其中參數a是下限,參數b是上限,生成的隨機數n: a <= n <= b
random.choice(sequence):從序列中獲取一個隨機元素
參數sequence表示一個有序類型(列表,元組,字符串)
'''
import httplib,json
import time
import threading
from random import randint,choice
#創建請求函數
def postRequest(threadNum):
postJson={
}
#定義需要進行發送的數據
postData=json.dumps(postJson)
#定義一些文件頭
headerdata = {
"content-type":"application/json",
}
#接口
requrl ="/v1/query"
#請求服務,例如:www.baidu.com
hostServer=""
#連接服務器
conn = httplib.HTTPConnection(hostServer)
#發送請求
conn.request(method="POST",url=requrl,body=postData,headers=headerdata)
#獲取請求響應
response=conn.getresponse()
#打印請求狀態
if response.status in range(200,300):
print u"線程"+str(threadNum)+u"狀態碼:"+str(response.status)
conn.close()
def run(threadNum,internTime,duration):
#創建數組存放線程
threads=[]
try:
#創建線程
for i in range(1,threadNum):
#針對函數創建線程
t=threading.Thread(target=postRequest,args=(i,))
#把創建的線程加入線程組
threads.append(t)
except Exception,e:
print e
try:
#啓動線程
for thread in threads:
thread.setDaemon(True)
thread.start()
time.sleep(internTime)
#等待所有線程結束
for thread in threads:
thread.join(duration)
except Exception,e:
print e
if __name__ == '__main__':
startime=time.strftime("%Y%m%d%H%M%S")
now=time.strftime("%Y%m%d%H%M%S")
duratiion=raw_input(u"輸入持續運行時間:")
while (startime+str(duratiion))!=now:
run(10,1,int(duratiion))
now=time.strftime("%Y%m%d%H%M%S")
運行結果:
寫到這裏,給大家推薦一個資源很全的python學習聚集地,點擊進入,這裏有資深程序員分享以前學習
心得,學習筆記,還有一線企業的工作經驗,且給大家精心整理一份python零基礎到項目實戰的資料,
每天給大家講解python最新的技術,前景,學習需要留言的小細節