python基础知识(四)——发送请求、接口关联
一、requests库
- python发送http的接口请求,需要使用requests库
- 客户端–>服务器发送请求需要:请求地址、请求方法、请求头、请求体
- 服务器–>客户端作出响应:http响应状态码,响应头,响应体
注:详细介绍请看
接口测试(一)基础
二、注册(示例仅供参考)
# 请求url
urlRegister = "http://47.115.15.198:7001/smarthome/user/register"
# 请求头
headerRegister = {"X-Lemonban-Media-Type":"lemonban.v2",
"Content-Type":"application/json"}
#请求体
dataRegister = {
"phone": "15219081994",
"pwd": "1234567a",
"rePwd": "1234567a",
"userName": "ding94",
"verificationCode": msgCode
}
1. 情景一:响应结果只有状态码
注:若请求体是json格式,首选json传参,即 requests.post( json = xxx )
#请求方法-post
responseRegister = requests.post(url=urlRegister, headers=headerRegister, json=dataRegister)
print(responseRegister)
2. 情景二:响应结果json格式、响应头、响应状态码
#请求方法-post
responseRegister = requests.post(url=urlRegister, headers=headerRegister, json=dataRegister).json()
print(responseRegister)
#获取响应头
responseHeaderRegister = requests.post(url=urlRegister,headers=headerRegister,json=dataRegister).headers
print(responseHeaderRegister)
#获取响应状态码
responseCodeRegister = requests.post(url=urlRegister,headers=headerRegister,json=dataRegister).status_code
print(responseCodeRegister)
三、接口关联
示例:根据响应结果,取token、id值
{
'code': '0',
'msg': '操作成功',
'data': {
'token_info': {
'token_type': 'Bearer',
'expires_in': '2023-01-04 21:25:56',
'token': 'eyJhbGciOiJIUzUxMiJ9.eyJ1c2VyX2lkIjoiOTQ3NzgiLCJleHAiOjE2NzI4MzkxMDN9.GZsxqxw64VSWuQvWr1PEPv2GIMVOGzE-0TFjz4vzyrLhP4VJ0b81CW3K4afl9k-xqdV4RPG0h3uJRG9GWS2m4g'
},
'phone': '15219081993',
'user_name': 'ding93',
'id': 94778,
'type': False
}
}
responseLogin = requests.post(url=urlLogin,headers=headerLogin,json=dataLogin).json()
- 方式一:通过字典嵌套取值
# 从登录响应体中取到token值内容,再赋值给token变量
token = responseLogin['data']['token_info']['token']
#从登录响应体中取到id值内容,再赋值给userId变量
userId = responseLogin['data']['id']
- 方式二:jsonpath表达式
token = jsonpath.jsonpath(responseLogin,"$.data.token_info.token")[0]
print(token)
userId = jsonpath.jsonpath(responseLogin,"$.data.id")[0]
print(userId)
- token、id值的关联使用
urlCom = "http://47.115.15.198:7001/smarthome/merchant/complete"
headerCom = {
"X-Lemonban-Media-Type":"lemonban.v2",
"Content-Type":"application/json",
"Authorization":"Bearer " + token
}
dataCom = {
"address": "湖南省长沙市岳麓区xx街道",
"establishDate": "2021-04-02",
"legalPerson": "韩信",
"licenseCode": "xh430646464sdfa",
"licenseUrl": "http://127.0.0.1/smarthome/aaa.jpg",
"merchantName": "青海文梅科技有限公司",
"merchantType": 2,
"registerAuthority": "城中区派出所",
"tel": "18888888888",
"userId": userId,
"validityDate": "2033-05-02"
}
#获取响应结果
responseCom = requests.put(url=urlCom,headers=headerCom,json=dataCom).json()
四、get请求
1. get请求,请求数据为query类型,应使用param进行传参
urlMsgCode = "http://47.115.15.198:7001/smarthome/verificationCode/message"
dataMsgCode = {"phone":"15219081994"}
headerMsgCode = {"X-Lemonban-Media-Type":"lemonban.v2"}
responseMsgCode = requests.get(url=urlMsgCode,params=dataMsgCode,headers=headerMsgCode).json()
print(responseMsgCode)
运行结果示例:
{
'code': '0',
'msg': '操作成功',
'data': '631812'
}