天天看點

使用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":{"詳細資料"}
           

若接口中做了并發處理,同時開啟多數線程時,就會觸發代碼中的并發處理邏輯(如提示:伺服器繁忙,請稍後再試!)