使用python请求接口(可进行并发测试)

python可以支持多个线程,所以可以利用python对写好的接口进行并发测试。请求接口代码如下:

#coding=utf-8
import requests
import json
import threading
import time
import uuid
class postrequests():
    def __init__(self):
        
        self.url = 'https://***.*****.com/user/user/login' #请求链接
        self.data = {'phone': '176*****286','code':'12***6'} #传递参数
        self.headers = {'content-type': 'application/json'} #请求头
        self.data = json.dumps(self.data)
 
    def post(self):
        try:
            r = requests.post(self.url, self.data, headers=self.headers)
            print(r.text)
        except Exception as e:
            print(e)
 
def kquan_bf():
    login = postrequests()
    return login.post()
    
 
try:
    i = 0
    # 开启线程数目
    tasks_number = 1
    print('测试启动')
    time1 = time.perf_counter()
    while i < tasks_number:
        t = threading.Thread(target=kquan_bf)
        t.start()
        i +=1
    time2 = time.perf_counter()
    times = time2 - time1
    print(times/tasks_number) #每次请求用时
except Exception as e:
    print(e)  #请求结果

结果显示:

测试启动
0.0005290000000000017
>>> {"code":0,"message":"操作成功","data":{"详细数据"}

若接口中做了并发处理,同时开启多数线程时,就会触发代码中的并发处理逻辑(如提示:服务器繁忙,请稍后再试!)

你可能感兴趣的:(python,php,python,python请求接口,python并发测试,PHP并发测试,并发测试)