1. 程式人生 > 實用技巧 >requests---介面自動化

requests---介面自動化

# 此程式碼是使用requests請求url

import requests

class ReqLogin:
    def auth(self):
        # 獲取token
        url = "http://xxxxx:xxx/xxx/xxxx/xxx"
        re = requests.post(url)
        print(re.json())
        # print(re.status_code)
        # print(re.json()['msg'])
        # print(re.json()['token'])
        self.token = re.json()['
token'] def token_not_login(self): url = "http://xxxxx:xxxxx/xxx/xxxx/xxx" headers = {"token": self.token, "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8", "User-Agent": "Apache-HttpClient/4.5.7 (Java/1.8.0_261)"} re = requests.post(url, headers=headers)
print(re.json()) # print(re.status_code) # print(re.json()['msg']) def reg(self): # 使用者註冊 headers = {"token": self.token} url1 = "http://xxxx:xxxx/xxx/xxxxx/xxxx" data = {"username": "amy8899", "pwd": "amy8899", "nickname": "amy8899", "describe": "amy8899
"} re = requests.post(url=url1, headers=headers, data=data) print(re.json()) def login(self): url2 = "http://xxxx:xxxx/xx/xxx/xxx" # 這三個引數是屬於比較重要--最好自行新增 # 當使用"Content-Type": "application/x-www-form-urlencoded; charset=UTF-8"時,下方post需使用data=進行傳參 # 當使用"Content-Type": "application/json; charset=UTF-8"時,代表資料是以json格式進行傳參的則使用json=進行傳參 headers = {"token": self.token, "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8", "User-Agent": "Apache-HttpClient/4.5.7 (Java/1.8.0_261)"} data = {"username": "david", "password": "david"} rep = requests.post(url=url2, headers=headers, data=data) print(rep.json()) # print('userid為', rep.json()['userid']) def re_login(self): # 二次登入 self.login() def token_logined(self): # token已登入 url = "http://xxx:xxx/xxx/xx/xxx" headers = {"token": self.token, "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8", "User-Agent": "Apache-HttpClient/4.5.7 (Java/1.8.0_261)"} re = requests.post(url, headers=headers) print(re.json()) # print(re.status_code) # print(re.json()['msg']) def get_user_info(self): # 該id未登入 url = "http://xxxx:xxxx/xxx/xx/xxxx" headers = {"token": self.token} data = {"id": "1"} re = requests.post(url=url, headers=headers, data=data) print(re.json()) if __name__ == '__main__': a = ReqLogin() a.auth() a.token_not_login() a.reg() a.login() a.re_login() a.token_logined() a.get_user_info()