import requests
import traceback
class Inert(object):
__left_limit, __right_limit = '${', '}'
def __init__(self, base_url: str):
self.base_url = base_url
self.session = requests.Session()
self.response = None
self.json_resp = None
self.params_pool = {}
def send_post_request(self, route: str, params=None):
new_params = self.__format_statement(params)
data = self.__format_params(params=new_params)
try:
self.response = self.session.post(self.base_url + route, data=data).text
except Exception:
print('[info] connect host error!')
if self.response:
try:
self.json_resp = eval(self.response)
except Exception:
print(traceback.print_exc())
def send_get_request(self, route: str, params=None):
try:
self.response = self.session.get(url=self.base_url + route, params=params).text
except Exception:
print('[info] connect host error')
if self.response:
try:
self.json_resp = eval(self.response)
except Exception:
print(traceback.print_exc())
def __format_params(self, params: str):
"""
:param params: 需要解析的參數
:return: 傳回一個dict對象
"""
new_dict = {}
if not params:
return
if isinstance(params, dict):
return params
try:
string_list = params.split("&")
for string in string_list:
index = string.find('=')
key = string[:index]
value = string[index + 1:]
new_dict[key] = value
return new_dict
except Exception:
print('[info] 參數有誤!')
def save_param(self, key_name):
"""
将參數添加到參數池中
:param key_name:新的鍵名
:return:
"""
try:
self.params_pool[key_name] = self.json_resp[key_name]
except Exception:
print("[info]參數不存在")
def add_headers(self, new_key, statement: str):
"""
将參數添加到請求頭中
:param new_key:添加至請求頭中的鍵名
:param statement:
:return:
"""
value = self.__format_statement(statement=statement)
try:
self.session.headers[new_key] = value
except Exception:
print('[info]參數不存在!')
def __format_statement(self, statement: str):
"""
:param statement: 對在參數池中的參數嘗試進行格式化
:return: 若statement存在或格式化失敗則傳回原語句,否則否會格式化後的語句
"""
if isinstance(statement, dict):
return statement
if statement:
for key in self.params_pool:
statement = statement.replace(
self.__left_limit + key + self.__right_limit,
self.params_pool[key]
)
return statement
def delimiter(self, lift: str, right: str):
"""
修改邊界符
:param lift: 左邊界符
:param right: 右邊界符
:return:
"""
self.__left_limit = lift
self.__right_limit = right