Python3接口性能测试实例代码

首先来看实例代码:

# -*- coding:utf-8 -*-import requestsimport datetimeimport timeimport threading'''allow_redirects = False禁止重定向,添加在request参数后get请求用params传参post请求,数据类型form,用data传参post请求,数据类型form,用data传参post请求,数据类型json,json传参timeout:请求超时时间,添加在request参数后nub = 10#设置并发线程数ResponseTime=float(result.elapsed.microseconds)/1000 #获取响应时间,单位msThinkTime = 0.5#设置思考时间AverageTime = "{:.3f}".format(float(sum(myrequest.times))/float(len(myrequest.times)))#计算数组的平均值,保留3位小数totaltime = float(hour)*60*60 + float(minute)*60 + float(second) #计算总的思考时间+请求时间'''class url_request:times = []error = []def weather_DC(self):myrequest=url_request()weatherinfo_search = 'https://restapi.amap.com/v3/weather/weatherInfo?parameters'params = {'key': 'cd1b11e80ffac05253196aa2a1233f25','city': 110101,'extensions': 'base','output': 'JSON'}result = requests.get(url=weatherinfo_search, params=params)print("状态码:",result.status_code)print("返回报文:",result.text)ResponseTime=float(result.elapsed.microseconds)/1000myrequest.times.append(ResponseTime)if result.status_code !=200 :myrequest.error.append("0")if __name__=='__main__':myrequest=url_request()threads = []starttime = datetime.datetime.now()print("请求开始时间:request start time %s" %starttime)nub = 10ThinkTime = 0.5for i in range(1, nub+1):t = threading.Thread(target=myrequest.weather_DC())threads.append(t)for t in threads:time.sleep(ThinkTime)print("线程数:thread %s" %t)t.setDaemon(True)t.start()t.join()endtime = datetime.datetime.now()print("请求结束时间:request end time %s" %endtime)time.sleep(3)AverageTime = "{:.3f}".format(float(sum(myrequest.times))/float(len(myrequest.times)))print("平均响应时间:Average Response Time %s ms" %AverageTime)usetime = str(endtime - starttime)hour = usetime.split(':').pop(0)minute = usetime.split(':').pop(1)second = usetime.split(':').pop(2)totaltime = float(hour)*60*60 + float(minute)*60 + float(second)print("并发数:Concurrent processing %s" %nub)print("#总共消耗的时间:use total time %s s" %(totaltime-float(nub*ThinkTime)))print("错误请求数:fail request %s s" %myrequest.error.count("0"))

实例扩展:
利用ruquest发送请求,利用多线程模拟并发
#!/user/bin/env python#coding=utf-8import requestsimport datetimeimport timeimport threadingclass url_request():times = []error = []def req(self,AppID,url):myreq=url_request()headers = {'User-Agent' : 'Mozilla/5.0 (Linux; Android 4.2.1; en-us; Nexus 4 Build/JOP40D) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.166 Mobile Safari/535.19'}payload = {'AppID':AppID,'CurrentURL':url}r = requests.post("http://xx.xxx.com/WeiXinJSAccessToken/json/WeChatJSTicket",headers=headers,data=https://www.it610.com/article/payload)ResponseTime=float(r.elapsed.microseconds)/1000 #获取响应时间,单位msmyreq.times.append(ResponseTime) #将响应时间写入数组if r.status_code !=200 :myreq.error.append("0")if __name__=='__main__':myreq=url_request()threads = []starttime = datetime.datetime.now()print "request start time %s" %starttime nub = 50#设置并发线程数ThinkTime = 0.5#设置思考时间for i in range(1, nub+1): t = threading.Thread(target=myreq.req, args=('12','http://m.ctrip.com/webapp/cpage/#mypoints'))threads.append(t)for t in threads:time.sleep(ThinkTime) #print "thread %s" %t #打印线程t.setDaemon(True)t.start()t.join()endtime = datetime.datetime.now()print "request end time %s" %endtimetime.sleep(3)AverageTime = "{:.3f}".format(float(sum(myreq.times))/float(len(myreq.times))) #计算数组的平均值,保留3位小数print "Average Response Time %s ms" %AverageTime #打印平均响应时间usetime = str(endtime - starttime)hour = usetime.split(':').pop(0)minute = usetime.split(':').pop(1)second = usetime.split(':').pop(2)totaltime = float(hour)*60*60 + float(minute)*60 + float(second) #计算总的思考时间+请求时间print "Concurrent processing %s" %nub #打印并发数print "use total time %s s" %(totaltime-float(nub*ThinkTime)) #打印总共消耗的时间print "fail request %s" %myreq.error.count("0") #打印错误请求数

request start time 2015-02-10 18:24:14.316000request end time 2015-02-10 18:24:39.769000Average Response Time 46.700 msConcurrent processing 50use total time 25.453 sfail request 1

【Python3接口性能测试实例代码】到此这篇关于Python3接口性能测试实例代码的文章就介绍到这了,更多相关Python3实现简单的接口性能测试内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

    推荐阅读