python api接口自动化模板

78 阅读1分钟

请求基类

提供的支持

  1. 提供 get, post 请求方法,并提供参数打印
  2. token 过期后,自动重新登录请求更新 token

文件名 base.py

import time
import requests
import json

class ApiTestRequest:
    
    def __init__(self, username:str, password:str):
        self.username = username
        self.password = password      
        self.max_retry = 3     
        self.__load_authorization()
        self.headers = {
            "Authorization": self.authorization,
            "Content-Type": "application/json",
            "Accept": "application/json",
            "Userinfo":"{\"lang\":\"ZH\"}"
        }   
    
    def __login(self):
        try:
            del self.headers["Authorization"]
        except:
            pass
        response = self._post("https://aboss.myatoto.com/atoto-user/user/mallUserLogin", data = {"username":self.username,"password": self.password,"source":28})
        dic = json.loads(response.text)
        data = dic['data']
        self.token = data["token"]
        self.tokenHead = data["tokenHead"]
        self.authorization = f"{self.tokenHead}{self.token}"
        self.__save_authorization()
    
    def __save_authorization(self):
        with open("authorization.txt", "w") as file:
            file.write(self.authorization)

    def __load_authorization(self):
        try:
            with open("authorization.txt", "r") as file:
                self.authorization = file.read()
        except:
            self.authorization = "Bearer 123"
    
    def _get(self, api:str, retry:int = 0):
        print("------------------------------------------------------------")
        print("get-->", api)
        start_time = time.time()
        response = requests.get(api, headers=self.headers)        
        end_time = time.time()
        # 计算毫秒耗时
        elapsed_time_ms = (end_time - start_time) * 1000
        print("response")
        print(json.dumps(response.json(), ensure_ascii=False, indent=4))
        print("耗时:", elapsed_time_ms, "毫秒")
        print()        

        result = self.__parse_error(response)
        if (result == False):
            if (retry < self.max_retry):
                retry += 1
                print(f"retry {retry} times")
            return self._get(api, retry = retry)
        return response
    
    def _post(self, api:str, data = None,  retry:int = 0):
        print("------------------------------------------------------------")
        print("post-->", api)
        print("head-->", self.headers)
        print("data:", json.dumps(data))
        start_time = time.time()
        response = requests.post(api, headers=self.headers, data = json.dumps(data))
        end_time = time.time()
        print("response")
        print(json.dumps(response.json(), ensure_ascii=False, indent=4))
        # 计算毫秒耗时
        elapsed_time_ms = (end_time - start_time) * 1000
        print("耗时:", elapsed_time_ms, "毫秒")
        print()       
        result = self.__parse_error(response)
        if (result == False):
            if (retry < self.max_retry):
                retry += 1
                print(f"retry {retry} times")
            return self._post(api, data = data, retry = retry)
        return response
    
    def __parse_error(self, response)->bool:
        dic = json.loads(response.text)
        code = dic['code']
        if code == 401: # 暂未登录或token已经过期
            self.__login()
            self.headers["Authorization"] = self.authorization
            return False
        return True                

具体请求业务类

文件名 my_request.py


import json

from base import ApiTestRequest

class MyApiRequest(ApiTestRequest):

    def __init__(self, username:str, password:str):
        super().__init__(username, password)       
        self.api_resource = "你的api1"
        self.api_resource_list = "你的api2"

    def test_api1(self):
        response = self._get(self.api_resource)
        dic = json.loads(response.text)
        data = dic['data']
        if len(data) >=1:
            item = data[0]
            self.resourceCategoryId = item["id"]
        return self

    def test_api2(self):
        data = {
            "resourceCategoryId": f"{self.resourceCategoryId}",
            "keyword": "",
        }
        self._post(self.api_resource_list, data = data)
        return self
       
            

MyApiRequest(username="用户名", password="密码").test_api1().test_api2()

结语

相信我,用起来会很方便