【python】简单的接口压测脚本

最近要优化个商城系统,没找到压测软件,就查资料用python写了个,效果还行。
效果图:
【python】简单的接口压测脚本_第1张图片
python代码(用的3):

import datetime
import json
import requests
import logging
import threading
import time
import sys
from time import sleep,ctime
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(thread)d - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)
 
reponse_time = []
OK = []
headers = {'token':'e835ea9248cadc906909973409e1d9a7','Content-Type':'application/json;charset=UTF-8'}; 

def getToken():
    loginR = requests.post('http://127.0.0.1:8000/XXXX/login', headers={'Content-Type':'application/json;charset=UTF-8'},data=json.dumps({"username":"123","password":"123456","uuid":"","captcha":"","userType":"","loginPlatform":"m"}), timeout=1000)
    loginR.raise_for_status()
    loginS = loginR.json()
    return loginS['token']
 
def urlPackage():
    reponse_time.clear()
    OK.clear()
    num = input('输入需要开启的线程数量:')
    url = 'http://127.0.0.1:8000/XXXX/pageList'  #地址
    params = {"orderState":"10","page":1,"limit":10,"createtimeStart":"","createtimeEnd":""}
    main(int(num),url,params)

class runScript():
    def API(self, url, params):
        try:
            r = requests.post(url, headers=headers,data=json.dumps(params), timeout=1000)
            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,url, params):
        # print(Restime.API(url, params)[0]['message'])
        res = self.API(url, params);
        reponse_time.append(res[1])
        datas = json.loads(res[2])["msg"]
        status = str(json.loads(res[2])["code"])
        if datas == 'success':
            OK.append(datas)
            logger.info('请求状态为:' + datas + ',状态码为:' + status)
        else:
            logger.info('请求状态为:' + datas + ',状态码为:' + status)
 
 
def test(url,params):
    Restime = runScript()
    Restime.circulation(url, params)
 
def main(num,url,params):
    # print("Starting at:",ctime())
    start_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    threads = []
    for i in range(num):
        t = threading.Thread(target=test,args=(url,params))
        threads.append(t)
    for t in range(num):
        threads[t].start()
    for j in range(num):
        threads[j].join()
    print("Starting at:",start_time)
    print("All done at:",datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
    print('响应次数:', len(reponse_time))
    print('正常响应次数:', len(OK))
    print('总响应最大时长:', max(reponse_time))
    print('总响应最小时长:', min(reponse_time))
    print('总响应时长:', sum(reponse_time))
    print('平均响应时长:', sum(reponse_time) / len(reponse_time))
    print('吞吐量:',num / sum(reponse_time))
    urlPackage()



    

if __name__ == '__main__':
    headers['token'] = getToken()
    urlPackage()`

你可能感兴趣的:(python,开发语言,压力测试,java)