在测试接口时需要有些接口登录后方可操作,这时需要将登录的session进行传递,可以直接获取登录后的cookie,也可以使用requests.Session();
通过方法session()进行传递
import json
import requests
def login():
url = "接口请求地址"
logininfo = json.dumps({"username":"admin","userpass":"1111"})
headers = {'Referer':'',
'X-Requested-with':'XMLHttpRequest',
'Content-Type':'application/json;charset=UTF-8'}
s = requests.session()
rps = s.post(url=url, data=logininfo,headers=headers)
print(rps.status_code)
print(rps.cookies.get_dict())
return s
def getUserInfo():
url = "接口请求地址2"
datainfo = json.dumps({"currentPage":1,"pagesize":15,"username":"","userDesc":""})
headers = {'Referer':'',
'X-Requested-with':'XMLHttpRequest',
'Content-Type':'application/json;charset=UTF-8'}
rps = login().post(url=url,data=datainfo,headers=headers)
print(rps.status_code)
print(rps.content)
print(rps.text)
getUserInfo()
使用requests的session会话对象来进行处理,会话对象让你能够跨请求保持某些参数,它也会在同一个Session实例发出的所有请求之间保持cookie,所以如果你向同一主机发送多个请求,底层的TCP连接将会被重用,从而带来显著的性能提升。