Python3接口性能测试实例代码


Posted in Python onJune 20, 2021

首先来看实例代码:

# -*- coding:utf-8 -*-


import requests
import datetime
import time
import 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 #获取响应时间,单位ms
ThinkTime = 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)/1000
        myrequest.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 = 10
    ThinkTime = 0.5
    for 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"))

实例扩展:

利用request发送请求,利用多线程模拟并发

#!/user/bin/env python
#coding=utf-8
import requests
import datetime
import time
import threading

class 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=payload)
        ResponseTime=float(r.elapsed.microseconds)/1000 #获取响应时间,单位ms
        myreq.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" %endtime  
    time.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.316000
request end time 2015-02-10 18:24:39.769000
Average Response Time 46.700 ms
Concurrent processing 50
use total time 25.453 s
fail request 1

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

Python 相关文章推荐
python中numpy包使用教程之数组和相关操作详解
Jul 30 Python
TF-IDF算法解析与Python实现方法详解
Nov 16 Python
python提取log文件内容并画出图表
Jul 08 Python
Python对接 xray 和微信实现自动告警
Sep 17 Python
python hashlib加密实现代码
Oct 17 Python
python3实现raspberry pi(树莓派)4驱小车控制程序
Feb 12 Python
pytorch模型存储的2种实现方法
Feb 14 Python
使用python无账号无限制获取企查查信息的实例代码
Apr 17 Python
在spyder IPython console中,运行代码加入参数的实例
Apr 20 Python
Python实现汇率转换操作
May 03 Python
如何在scrapy中集成selenium爬取网页的方法
Nov 18 Python
Python实现简单的2048小游戏
Mar 01 Python
使用Djongo模块在Django中使用MongoDB数据库
python自动计算图像数据集的RGB均值
详解如何用Python实现感知器算法
python中24小时制转换为12小时制的方法
Jun 18 #Python
用Python selenium实现淘宝抢单机器人
python中pandas对多列进行分组统计的实现
python 常用的异步框架汇总整理
Jun 18 #Python
You might like
PHP在字符串中查找指定字符串并删除的代码
2008/10/02 PHP
PHP中常用的输出函数总结
2014/09/22 PHP
腾讯CMEM的PHP扩展编译安装方法
2015/09/25 PHP
laravel学习教程之关联模型
2016/07/30 PHP
PHP实现八皇后算法
2019/05/06 PHP
JavaScript实现GriwView单列全选(自写代码)
2013/05/13 Javascript
原始XMLHttpRequest方法详情回顾
2013/11/28 Javascript
instanceof和typeof运算符的区别详解
2014/01/06 Javascript
jQuery实现鼠标悬停显示提示信息窗口的方法
2015/04/30 Javascript
Nodejs中使用phantom将html转为pdf或图片格式的方法
2017/09/18 NodeJs
基于滚动条位置判断的简单实例
2017/12/14 Javascript
angularjs实现table增加tr的方法
2018/02/27 Javascript
vue 做移动端微信公众号采坑经验记录
2018/04/26 Javascript
vue2.0 + ele的循环表单及验证字段方法
2018/09/18 Javascript
详解js创建对象的几种方式和对象方法
2021/03/01 Javascript
python 回调函数和回调方法的实现分析
2016/03/23 Python
python中defaultdict的用法详解
2017/06/07 Python
Python之多线程爬虫抓取网页图片的示例代码
2018/01/10 Python
Django进阶之CSRF的解决
2018/08/01 Python
Python3.5迭代器与生成器用法实例分析
2019/04/30 Python
Python数据类型之List列表实例详解
2019/05/08 Python
Python3+Appium安装使用教程
2019/07/05 Python
Python Opencv提取图片中某种颜色组成的图形的方法
2019/09/19 Python
python requests模拟登陆github的实现方法
2019/12/26 Python
django rest framework serializer返回时间自动格式化方法
2020/03/31 Python
在python中使用nohup命令说明
2020/04/16 Python
python pandas dataframe 去重函数的具体使用
2020/07/20 Python
如何用Java实现列出某个目录下的所有子目录
2015/07/20 面试题
社会学专业求职信
2014/07/17 职场文书
四年级学生期末评语
2014/12/26 职场文书
员工工作能力评语
2014/12/31 职场文书
营销计划书范文
2015/01/17 职场文书
消防安全主题班会
2015/08/12 职场文书
2016年中秋节寄语大全
2015/12/07 职场文书
代码解析React中setState同步和异步问题
2021/06/03 Javascript
MySQL 数据类型详情
2021/11/11 MySQL