python实现接口压力测试

python实现接口压力测试

直接上代码:

python 复制代码
# -*- coding: utf-8 -*-

import json
import requests
import logging

logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)

restime = []
OK=[]
class Interface_pressure_test():
    def API(self,URL2,param):
        try:
            r = requests.get(URL2, params=param, timeout=10)
            r.raise_for_status()  # 如果响应状态码不是 200,就主动抛出异常
        except requests.RequestException as e:
            print(e)
        else:
            js = json.dumps(r.json())
            return [r.json(), r.elapsed.total_seconds(),js]

    def circulation(self,num,URL2,param):
        for i in range(int(num)):
            restime.append(Interface_pressure_test.API(URL2,param)[1])
            if json.loads(Interface_pressure_test.API(URL2, param)[2])["message"]=='ok':
                OK.append(json.loads(Interface_pressure_test.API(URL2, param)[2])["message"])
                logger.info('请求第' + str(i+1) + '次,请求'+json.loads(Interface_pressure_test.API(URL2, param)[2])["message"]+',状态码:'+json.loads(Interface_pressure_test.API(URL2, param)[2])["status"])
            else:
                logger.info('请求第' + str(i+1) + '次,请求' + json.loads(Interface_pressure_test.API(URL2, param)[2])["message"] + ',状态码:' +
                            json.loads(Interface_pressure_test.API(URL2, param)[2])["status"])
        print('测试次数:',num)
        print('响应次数:', len(restime))
        print('正常响应次数:', len(OK))
        print('总响应最大时长:', max(restime))
        print('总响应最小时长:', min(restime))
        print('总响应时长:', sum(restime))
        print('平均响应时长:', sum(restime) / len(restime))

if __name__ == '__main__':
    Interface_pressure_test = Interface_pressure_test()
    num = input('请输入次数:') #压力测试次数
    URL2 = 'http://www.kuaidi100.com/query'  #地址
    param = {'type' : 'zhongtong' , 'postid' :'73116039505988' }  #参数
    Interface_pressure_test.circulation(num,URL2,param)
    input('Press Enter to exit...') 

输出20次压测结果如下:

相关推荐
默_笙5 天前
🍙 给每个请求过安检:FastAPI 是怎么把校验写进类型注解的
python
小羊没烦恼!5 天前
初探性能优化——2个月到4小时的性能提升
java·开发语言·windows·算法·c#
qq_426003965 天前
启动playwright录制codegen生成自动化测试脚本
python·自动化
虎头金猫5 天前
4K 视频总卡在公网带宽?用 N1 + OpenList 把网盘播放链路重新理顺
运维·服务器·网络·python·容器·beautifulsoup·pandas
长沙三为智能科技5 天前
家政小程序开发从0到上线:五阶段交付流程与验收清单
python
伞伞悦读5 天前
【第38期】Python 模块与包详解:import、from、模块搜索路径、包结构和 __init__
开发语言·python
只睡四小时5 天前
Canvas 弹道联机实战:700 行 + 固定时间步长
python·websocket·html5·游戏开发·canvas
C语言小火车5 天前
C/C++ 为什么需要编译器?
开发语言·c++
奇思妙想聪明勤奋的小羊5 天前
DeepAgents第5章:子Agent 与上下文隔离—让 Agent学会委派
人工智能·python·学习·语言模型
lpfasd1235 天前
2026年第38周GitHub趋势周报
python·科技·github