只需要安装requests和json
import requests
import json
【GET请求】
"""GET方法请求"""
url = 'http://localhost/get'
resp = requests.get(url)
print(resp.json()) # 打印返回为json
print(resp.content) # 打印返回为二进制
【POST请求】
"""POST方法请求,请求数据为json,返回数据以json格式输出"""
url = 'http://localhost/post_json'
param = {
"param1": 'param1',
"pageNum": 2,
"pageSize": 5
}
json_str = json.dumps(param)
headers = {"Content-Type": "application/json"}
resp = requests.post(url, data=json_str, headers=headers)
print(resp.json()) # 打印返回为json
print(resp.content) # 打印返回为二进制
其他请求如DELETE,PUT都是一样,即简单又易懂。
【请求带token】
请求先登录拿到token,然后再带token请求下一个
"""登录"""
url = 'http://localhost/login'
param = {
"username": phone,
"password": password
}
json_str = json.dumps(param)
headers = {"Content-Type": "application/json"}
resp = requests.post(url, data=json_str, headers=headers)
print('token:',resp.json())
toekn=resp.json()['token']
"""带上token请求"""
url = 'http://localhost/test'
param = {
'param1': '测试',
'param2': " "
}
json_str = json.dumps(param)
#请求头带token
headers = {"Content-Type": "application/json", "Authorization": token}
resp = requests.post(url, data=json_str, headers=headers)
print(resp.json())
【循环测试请求】
"""登录"""
url = 'http://localhost/login'
param = {
"username": phone,
"password": password
}
json_str = json.dumps(param)
headers = {"Content-Type": "application/json"}
resp = requests.post(url, data=json_str, headers=headers)
print('token:',resp.json())
toekn=resp.json()['token']
"""带上token请求"""
url = 'http://localhost/test'
param = {
'param1': '测试',
'param2': " "
}
json_str = json.dumps(param)
#请求头带token
headers = {"Content-Type": "application/json", "Authorization": token}
# 循环请求
for i in range(100):
resp = requests.post(url, data=json_str, headers=headers)
print(resp.json())
用python代替postman做测试可以做到随心应手,不管是怎样的请求,代码量即少,自己维护。