python多线程对url api接口进行压力测试代码

代码语言:python

所属分类:其他

代码描述:python多线程对url api接口进行压力测试代码,可设置线程数及真确接口地址返回数据。

代码标签: python 多线程 url api 接口 压力 测试

下面为部分代码预览,完整代码请点击下载或在bfwstudio webide中打开

import base64
import os
import urllib
import numpy as np
import requests, time, json, threading, random
 
 
class Presstest(object):
    """
    并发压力测试 
    """
    def __init__(self,  press_url):
        self.press_url = press_url
 
    def test_interface(self):
        '''压测接口'''
        global INDEX
        INDEX += 1
 
        global ERROR_NUM
        global TIME_LENS
        try:
            start = time.time()
            payload = {'img_datas': ""}
            response_content = self.do_request(self.press_url, payload)
            result = json.loads(response_content)
            end = time.time()
            TIME_LENS.append(end - start)
            print('end')
        except Exception as e:
            ERROR_NUM += 1
            print(e)
 
    def test_onework(self):
        '''一次并发处理单个任务'''
        i = 0
        while i < ONE_WORKER_NUM:
            i += 1
            self.test_interface()
        time.sleep(LOOP_SLEEP)
 
    def do_request(self, url, payload):
        '''通用http获取webapi请求结果方法'''
        headers = {
            'Content-Type': 'application/json; charset=UTF-8',
        }
        request = urllib.request.Request(url, json.dumps(payload).encode("utf-8"), headers=headers)
        retry_num = 0
        while retry_num < 3:
            response = urllib.request.urlopen(request, timeout=300)
            if not response or response.status == 421:
                time.sleep(1)
                retry_num = retry_num + 1
                continue
            else:
    .........完整代码请登录后点击上方下载按钮下载查看

网友评论0