# _*_ coding:utf-8 _*_
"""
file_name:test_api
author:Sam
date:2020/4/17
content:使用多线程测试接口(并发请求)
"""
import requests
import json
from threading import Thread
class ThreadSpider(object):
def __init__(self, **kw):
self.header = {
'User-Agent':
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.132 Safari/537.36'
}
if 'request_url' in kw:
self.url = kw['request_url']
else:
self.url = ''
if 'request_param' in kw:
self.param = kw['request_param']
else:
self.param = {}
# 线程数量,主线程占了一个,所以这里减去一个
if 'thread_count' in kw:
self.thread_count = kw['thread_count'] - 1
else:
self.thread_count = 9
if 'method' in kw:
self.method = kw['method']
else:
self.method = 'post'
def main(self):
# 创建获取url的线程
url_thread = Thread(target=self.request)
# 详情线程组
detail_thread = []
for i in range(self.thread_count):
thread2 = Thread(target=self.request)
detail_thread.append(thread2)
# 开启url线程
url_thread.start()
for i in range(self.thread_count):
# 开启详情进程
detail_thread[i].start()
# 等待所有子进程结束
url_thread.join()
for i in range(self.thread_count):
detail_thread[i].join()
def request(self):
if self.method == 'post':
response = requests.post(self.url, data=self.param, headers=self.header)
else:
response = requests.get(self.url, data=self.param, headers=self.header)
data = response.text
# 打印接口返回的数据
print(data)
if __name__ == '__main__':
# 接口地址
url = "http://www.baidu.com/"
# 设置参数
param = {}
# 设置请求方式
method = 'get'
ThreadSpider = ThreadSpider(request_url=url, request_param=param, method=method)
ThreadSpider.main()
本文主要是用到python的多线程,可以实现同一时间多次请求同一个接口,对接口进行并发测试。