1 # -*- coding:utf-8 -*-
2 import json,requests
3 import settings
4
5
6 class BaseApi(object):
7 url = ""
8 base_url= settings.API_TEST_BASE_URL
9
10 def __init__(self,url_params=None):
11 if not url_params:
12 url_params = []
13 self.url_params = url_params
14 self.response = None
15 self.base_url = self.base_url
16
17 # 拼接url
18 def api_url(self):
19 if not self.url:
20 raise RuntimeError("no url been set")
21 return self._get_url()
22
23 def _get_url(self):
24 format_url = self.url.format(self.url_params)
25 return "{0}{1}".format(self.base_url, format_url)
26
27 # 封装POST请求类型
28 def post(self, data=None):
29 if not data:
30 data = {}
31 base_param = self.build_base_param()
32 custom_param = self.build_custom_param(data)
33 data.update(base_param)
34 data.update(custom_param)
35 self.response = requests.post(url=self.api_url(), data=data, headers=settings.HEADERS)
36 return self.response
37
38 # 封装GET请求类型
39 def get(self,data=None):
40 if not data:
41 data={}
42 base_param = self.build_base_param()
43 custom_param = self.build_custom_param(data)
44 data.update(base_param)
45 data.update(custom_param)
46 response = requests.get(url=self.api_url(),params=data)
47 return self.response
48
49 # 获取回参中状态码
50 def get_code(self):
51 if self.response:
52 return json.loads(self.response.text)["code"]
53
54 # 获取HTTP状态码
55 def get_status_code(self):
56 if self.response:
57 return self.response.status_code
58
59 # 获取回参中message
60 def get_response_message(self):
61 if self.response:
62 return json.loads(self.response.text)["msg"]
63
64 # 所有接口共有的入参,比如:app_version、token等
65 def build_base_param(self):
66 return {
67 "app_version": SETTINGS.APP_VERSION,
68 "token":""
69 }
70
71 # 被测接口除公共参数外所需的其余参数
72 def build_custom_param(self, data):
73 return {}