登录接口,jsonpath提取响应结果,token鉴权处理
import time import uuid import requests import pprint from jsonpath import jsonpath from test_image_code import ImageCode class Manage: def __init__(self): self.header = {"locale": "zh_CN"} self.login_url = '{}/adminLogin' self.activity_url = '{}/sys/webConfig/getActivity' self.image_code = ImageCode() def login(self): # 生成uuid session_uuid = str(uuid.uuid4()) # 调用图片验证码方法 image_code = self.image_code.get_image_code(uuid=session_uuid) data = { "t": int(time.time() * 1000), "principal": "", "credentials": "", "sessionUUID": session_uuid, "imageCode": image_code } res = requests.post(url=self.login_url, json=data) # 从响应结果中获取鉴权的token,jsonpath返回的是list,需要通过索引取值,取第一个 token = jsonpath(res.json(), "$..access_token")[0] print(token) # 将token拼接为指定的格式,存放在请求头中 self.header["Authorization"] = "bearer{}".format(token) print("请求头:", self.header) # print("登录接口返回", res.json()) return self.header def get_activity(self): self.login() res = requests.get(url=self.activity_url, header=self.header) pprint.pprint(res.json()) if __name__ == '__main__': rel = Manage() rel.login()