一、Post請(qǐng)求
1、使用python發(fā)送一個(gè)Post請(qǐng)求
有時(shí)候遇到請(qǐng)求url中有很多參數(shù)。
1.1 示例1
accounts和pwd請(qǐng)到http://shop-xo.hctestedu.com/注冊(cè)。
import requests
# 請(qǐng)求體
data = {
"accounts": "xx",
"pwd": "xxx",
"type": "username"
}
# 只有php項(xiàng)目需要application和application_client_type
# 寫法一, 在請(qǐng)求Url中帶上所有參數(shù),application和application_client_type,用&隔開
response = requests.post(url="http://shop-xo.hctestedu.com/index.php?"
"s=api/user/login"
"&application=app"
"&applicaiton_client_type=weixin", json=data)
# 輸出響應(yīng)結(jié)果
print(response.text)
執(zhí)行結(jié)果:
{"msg":"登錄成功","code":0,"data":{"id":"7073","username":"xx","nickname":"","mobile":"","email":"","avatar":"http:\/\/shop-xo.hctestedu.com\/static\/index\/default\/images\/default-user-avatar.jpg","alipay_openid":"","weixin_openid":"","weixin_unionid":"","weixin_web_openid":"","baidu_openid":"","toutiao_openid":"","qq_openid":"","qq_unionid":"","integral":"189","locking_integral":"0","referrer":"0","add_time":"1646195490","add_time_text":"2022-03-02 12:31:30","mobile_security":"","email_security":"","user_name_view":"xx","is_mandatory_bind_mobile":0,"token":"xxxxxx"}}
1.2 示例2
使用不定長(zhǎng)參數(shù) params,將url中需要的參數(shù)單獨(dú)封裝。
import requests
# 請(qǐng)求體
data = {
"accounts": "xx",
"pwd": "xxx",
"type": "username"
}
# 使用不定長(zhǎng)參數(shù)params
param_data = {
"application": "app",
"application_client_type": "weixin"
}
# 寫法2:使用不定長(zhǎng)參數(shù)params
response = requests.post(url="http://shop-xo.hctestedu.com/index.php?"
"s=api/user/login", params=param_data, json=data)
# 輸出響應(yīng)結(jié)果
print(response.text)
執(zhí)行結(jié)果:
{"msg":"登錄成功","code":0,"data":{"id":"22299","username":"xx","nickname":"","mobile":"","email":"","avatar":"http:\/\/shop-xo.hctestedu.com\/static\/index\/default\/images\/default-user-avatar.jpg","alipay_openid":"","weixin_openid":"","weixin_unionid":"","weixin_web_openid":"","baidu_openid":"","toutiao_openid":"","qq_openid":"","qq_unionid":"","integral":"0","locking_integral":"0","referrer":"0","add_time":"1678005098","add_time_text":"2023-03-05 16:31:38","mobile_security":"","email_security":"","user_name_view":"xx","is_mandatory_bind_mobile":0,"token":"xxxxx"}}
二、獲取Response body
1、response.text
用type()查看response.text的類型,是str
import requests
# 請(qǐng)求體
data = {
"accounts": "xx",
"pwd": "xxx",
"type": "username"
}
# 使用不定長(zhǎng)參數(shù)params
param_data = {
"application": "app",
"application_client_type": "weixin"
}
# 寫法2:使用不定長(zhǎng)參數(shù)params
response = requests.post(url="http://shop-xo.hctestedu.com/index.php?"
"s=api/user/login", params=param_data, json=data)
# 輸出響應(yīng)結(jié)果
print(response.text)
print(type(response.text))
執(zhí)行結(jié)果:
{"msg":"登錄成功","code":0,"data":{"id":"22299","username":"xx","nickname":"","mobile":"","email":"","avatar":"http:\/\/shop-xo.hctestedu.com\/static\/index\/default\/images\/default-user-avatar.jpg","alipay_openid":"","weixin_openid":"","weixin_unionid":"","weixin_web_openid":"","baidu_openid":"","toutiao_openid":"","qq_openid":"","qq_unionid":"","integral":"0","locking_integral":"0","referrer":"0","add_time":"1678005098","add_time_text":"2023-03-05 16:31:38","mobile_security":"","email_security":"","user_name_view":"xx","is_mandatory_bind_mobile":0,"token":"xxxxx"}}
<class 'str'>
2、response.json()
用type()查看response.json()的類型,是dict
import requests
# 請(qǐng)求體
data = {
"accounts": "xx",
"pwd": "xxx",
"type": "username"
}
# 使用不定長(zhǎng)參數(shù)params
param_data = {
"application": "app",
"application_client_type": "weixin"
}
# 寫法2:使用不定長(zhǎng)參數(shù)params
response = requests.post(url="http://shop-xo.hctestedu.com/index.php?"
"s=api/user/login", params=param_data, json=data)
# 輸出響應(yīng)結(jié)果
print(response.json())
print(type(response.json()))
執(zhí)行結(jié)果:
{"msg":"登錄成功","code":0,"data":{"id":"22299","username":"xx","nickname":"","mobile":"","email":"","avatar":"http:\/\/shop-xo.hctestedu.com\/static\/index\/default\/images\/default-user-avatar.jpg","alipay_openid":"","weixin_openid":"","weixin_unionid":"","weixin_web_openid":"","baidu_openid":"","toutiao_openid":"","qq_openid":"","qq_unionid":"","integral":"0","locking_integral":"0","referrer":"0","add_time":"1678005098","add_time_text":"2023-03-05 16:31:38","mobile_security":"","email_security":"","user_name_view":"xx","is_mandatory_bind_mobile":0,"token":"xxxxx"}}
<class 'dict'>
三、獲取響應(yīng)狀態(tài)碼:res.status_code
print(response.status_code)
執(zhí)行結(jié)果:
200
更多狀態(tài)碼:
狀態(tài)代碼有三位數(shù)字組成,第一個(gè)數(shù)字定義了響應(yīng)的類別,共分五種類別:
1xx:指示信息--表示請(qǐng)求已接收,繼續(xù)處理
2xx:成功--表示請(qǐng)求已被成功接收、理解、接受
3xx:重定向--要完成請(qǐng)求必須進(jìn)行更進(jìn)一步的操作
4xx:客戶端錯(cuò)誤--請(qǐng)求有語法錯(cuò)誤或請(qǐng)求無法實(shí)現(xiàn)
5xx:服務(wù)器端錯(cuò)誤--服務(wù)器未能實(shí)現(xiàn)合法的請(qǐng)求
常見狀態(tài)碼:
200 OK //客戶端請(qǐng)求成功
400 Bad Request //客戶端請(qǐng)求有語法錯(cuò)誤,不能被服務(wù)器所理解
401 Unauthorized //請(qǐng)求未經(jīng)授權(quán),這個(gè)狀態(tài)代碼必須和WWW-Authenticate報(bào)頭域一起使用
403 Forbidden //服務(wù)器收到請(qǐng)求,但是拒絕提供服務(wù)
404 Not Found //請(qǐng)求資源不存在,eg:輸入了錯(cuò)誤的URL
500 Internal Server Error //服務(wù)器發(fā)生不可預(yù)期的錯(cuò)誤
503 Server Unavailable //服務(wù)器當(dāng)前不能處理客戶端的請(qǐng)求,一段時(shí)間后可能恢復(fù)正常
四、獲取響應(yīng)cookies:res.cookies
print(response.cookies)
執(zhí)行結(jié)果:
<RequestsCookieJar[<Cookie PHPSESSID=92ppj01t00t4v142rd8fsmos7k for shop-xo.hctestedu.com/>]>
五、獲取響應(yīng)headers:res.headers
print(response.headers)
執(zhí)行結(jié)果:
{'Server': 'nginx', 'Date': 'Sun, 05 Mar 2023 10:04:02 GMT', 'Content-Type': 'application/json; charset=utf-8', 'Transfer-Encoding': 'chunked', 'Connection': 'keep-alive', 'Set-Cookie': 'PHPSESSID=ul9qsgallg17d5am81q08pfhj0; path=/; HttpOnly', 'Expires': 'Thu, 19 Nov 1981 08:52:00 GMT', 'Cache-Control': 'no-store, no-cache, must-revalidate', 'Pragma': 'no-cache'}
六、獲取響應(yīng)結(jié)果原始內(nèi)容:res.content
content,沒有經(jīng)過編譯的,以字節(jié)的形式展示。而上述提到的text是編譯過的。自動(dòng)找到請(qǐng)求頭中的編碼格式,進(jìn)行解析。
print(response.content)
print(type(response.content))
執(zhí)行結(jié)果:
b'{"msg":"\xe7\x99\xbb\xe5\xbd\x95\xe6\x88\x90\xe5\x8a\x9f","code":0,"data":{"id":"22299","username":"xxxxx","nickname":"","mobile":"","email":"","avatar":"http:\\/\\/shop-xo.hctestedu.com\\/static\\/index\\/default\\/images\\/default-user-avatar.jpg","alipay_openid":"","weixin_openid":"","weixin_unionid":"","weixin_web_openid":"","baidu_openid":"","toutiao_openid":"","qq_openid":"","qq_unionid":"","integral":"0","locking_integral":"0","referrer":"0","add_time":"1678005098","add_time_text":"2023-03-05 16:31:38","mobile_security":"","email_security":"","user_name_view":"xxxxx","is_mandatory_bind_mobile":0,"token":"d653d78ac417f65e1cd38c6f3e220341"}}'
<class 'bytes'>
content還支持手動(dòng)的編碼,例如使用utf-8編碼,編碼后的是str類型,json本質(zhì)是一種字符串類型
resp = response.content.decode("utf-8")
print(resp)
print(type(resp))
執(zhí)行結(jié)果:
{"msg":"登錄成功","code":0,"data":{"id":"22299","username":"xxxxx","nickname":"","mobile":"","email":"","avatar":"http:\/\/shop-xo.hctestedu.com\/static\/index\/default\/images\/default-user-avatar.jpg","alipay_openid":"","weixin_openid":"","weixin_unionid":"","weixin_web_openid":"","baidu_openid":"","toutiao_openid":"","qq_openid":"","qq_unionid":"","integral":"0","locking_integral":"0","referrer":"0","add_time":"1678005098","add_time_text":"2023-03-05 16:31:38","mobile_security":"","email_security":"","user_name_view":"xxxxx","is_mandatory_bind_mobile":0,"token":"d653d78ac417f65e1cd38c6f3e220341"}}
<class 'str'>
七、獲取響應(yīng)結(jié)果:最原生的狀態(tài),對(duì)象在內(nèi)存中的地址:res.raw
print(response.raw)
print(type(response.raw))
執(zhí)行結(jié)果:
<urllib3.response.HTTPResponse object at 0x0000023317D8D880>
<class 'urllib3.response.HTTPResponse'>
八、解析響應(yīng)數(shù)據(jù)
響應(yīng)數(shù)據(jù)如下:
{
"msg": "登錄成功",
"code": 0,
"data": {
"id": "22299",
"username": "Summer",
"nickname": "",
"mobile": "",
"email": "",
"avatar": "http:\/\/shop-xo.hctestedu.com\/static\/index\/default\/images\/default-user-avatar.jpg",
"alipay_openid": "",
"weixin_openid": "",
"weixin_unionid": "",
"weixin_web_openid": "",
"baidu_openid": "",
"toutiao_openid": "",
"qq_openid": "",
"qq_unionid": "",
"integral": "0",
"locking_integral": "0",
"referrer": "0",
"add_time": "1678005098",
"add_time_text": "2023-03-05 16:31:38",
"mobile_security": "",
"email_security": "",
"user_name_view": "chengcheng",
"is_mandatory_bind_mobile": 0,
"token": "d653d78ac417f65e1cd38c6f3e220341"
}
}
通常我們獲取響應(yīng)數(shù)據(jù)后,是需要進(jìn)行結(jié)果驗(yàn)證的。例如,我想從登錄接口的響應(yīng)中拿到token,供后面的接口請(qǐng)求鑒權(quán)使用。
1、字典方式解析及其缺點(diǎn)
上面已經(jīng)講到,可以使用response.json()方法拿到一個(gè)字典。既然是字典,就可以用處理字典的方式來獲取某個(gè)字段的值。
resp = response.json()
token = resp["data"]["token"]
print(token )
執(zhí)行結(jié)果:
d653d78ac417f65e1cd38c6f3e220341
字典解析的缺點(diǎn):如果接口數(shù)據(jù)異常,響應(yīng)體缺少某個(gè)字段,就會(huì)發(fā)生keyerror,導(dǎo)致程序異常。
resp = response.json()
token = resp["data"]["token1"]
print(token )
執(zhí)行結(jié)果:
Traceback (most recent call last):
File "E:\Coding\python-workspace\Interface_test\first_requests.py", line 128, in <module>
token = resp["data"]["token1"]
KeyError: 'token1'
2、Jsonpath表達(dá)式解析及其優(yōu)點(diǎn)
上面的響應(yīng)body結(jié)構(gòu)比較簡(jiǎn)單,如果我們要解析特別復(fù)雜的響應(yīng)體,通過字典方式就很復(fù)雜。這個(gè)時(shí)候更推薦jsonpath。需要引入jsonpath庫(kù)。
import jsonpath
resp = response.json() # 將返回值轉(zhuǎn)換成字典格式
token = jsonpath.jsonpath(resp, '$..token') # token的jsonpath表達(dá)式:$..token
print(token)
執(zhí)行結(jié)果:
['d653d78ac417f65e1cd38c6f3e220341']
通過結(jié)果來看,獲取到的token是只有一個(gè)元素的列表。我們要想拿到token通過下標(biāo)訪問。
修改上述代碼:
import jsonpath
resp = response.json() # 將返回值轉(zhuǎn)換成字典格式
token = jsonpath.jsonpath(resp, '$..token') # token的jsonpath表達(dá)式:$..token
print(token[0])
執(zhí)行結(jié)果:
d653d78ac417f65e1cd38c6f3e220341
Jsonpath表達(dá)式解析的優(yōu)點(diǎn):如果響應(yīng)體缺少某個(gè)字段,通過Jsonpath表達(dá)式解析不到結(jié)果,就會(huì)返回False,永遠(yuǎn)不會(huì)發(fā)生異常。我們可根據(jù)返回結(jié)果進(jìn)行后續(xù)處理。
import jsonpath
resp = response.json() # 將返回值轉(zhuǎn)換成字典格式
# 使用錯(cuò)誤的jsonpath表達(dá)式
token = jsonpath.jsonpath(resp, '$..token1') # token的jsonpath表達(dá)式:$..token1
if isinstance(token, List):
print(f'可以解析到token,值為:{token[0]}')
else:
print(f'解析不到token,結(jié)果為:{token}')
# 使用正確的jsonpath表達(dá)式
token = jsonpath.jsonpath(resp, '$..token') # token的jsonpath表達(dá)式:$..token
if isinstance(token, List):
print(f'可以解析到token,值為:{token[0]}')
else:
print(f'解析不到token,結(jié)果為:{token}')
執(zhí)行結(jié)果:
解析不到token,結(jié)果為:False
可以解析到token,值為:d653d78ac417f65e1cd38c6f3e220341
3、如何知道自己寫的jsonpath表達(dá)式是否正確呢?
jsonpath在線校驗(yàn)工具:http://jsonpath.com/
將response粘貼在Inputs區(qū)域,在JSONPath區(qū)域輸入表達(dá)式,在Evaluation Results區(qū)域查看是否解析到期望的值。當(dāng)解析不到值時(shí),返回的是空列表(No match)jsonpath表達(dá)式語法
九、獲取請(qǐng)求的信息
print(f'請(qǐng)求url:{response.request.url}')
print(f'請(qǐng)求方法:{response.request.method}')
print(f'請(qǐng)求Header:{response.request.headers}')
print(f'請(qǐng)求路徑:{response.request.path_url}')
執(zhí)行結(jié)果:
請(qǐng)求url:http://shop-xo.hctestedu.com/index.php?s=api/user/login&application=app&application_client_type=weixin
請(qǐng)求方法:POST
請(qǐng)求Header:{'User-Agent': 'python-requests/2.28.1', 'Accept-Encoding': 'gzip, deflate', 'Accept': '*/*', 'Connection': 'keep-alive', 'Content-Length': '69', 'Content-Type': 'application/json'}
請(qǐng)求路徑:/index.php?s=api/user/login&application=app&application_client_type=weixin
十、json=data 和 data=data 參數(shù)區(qū)別
接口電商項(xiàng)目后臺(tái)代碼(PHP)中,json=data以及data=data這2種參數(shù)類型都可以接收。在實(shí)際項(xiàng)目應(yīng)用中,常見的報(bào)文格式是application/json。因此最常使用的是json=data
1、json=data
請(qǐng)求頭默認(rèn)為:Content-Type=application/json
url = 'http://shop-xo.hctestedu.com/index.php?s=api/user/login'
res = requests.post(url=url, json=data, params=param_data)
# 查看請(qǐng)求中的請(qǐng)求頭信息,Content-Type=application/json
print(res.request.headers)
print(res.text)
執(zhí)行結(jié)果:
{'User-Agent': 'python-requests/2.28.1', 'Accept-Encoding': 'gzip, deflate', 'Accept': '*/*', 'Connection': 'keep-alive', 'Content-Length': '69', 'Content-Type': 'application/json'}
{"msg":"登錄成功","code":0,"data":{"id":"22299","username":"xxxxx","nickname":"","mobile":"","email":"","avatar":"http:\/\/shop-xo.hctestedu.com\/static\/index\/default\/images\/default-user-avatar.jpg","alipay_openid":"","weixin_openid":"","weixin_unionid":"","weixin_web_openid":"","baidu_openid":"","toutiao_openid":"","qq_openid":"","qq_unionid":"","integral":"0","locking_integral":"0","referrer":"0","add_time":"1678005098","add_time_text":"2023-03-05 16:31:38","mobile_security":"","email_security":"","user_name_view":"xxxxx","is_mandatory_bind_mobile":0,"token":"d653d78ac417f65e1cd38c6f3e220341"}}
2、data=data
請(qǐng)求頭默認(rèn)為:application/x-www-form-urlencoded
url = 'http://shop-xo.hctestedu.com/index.php?s=api/user/login'
res = requests.post(url=url, data=data, params=param_data)
# 查看請(qǐng)求中的請(qǐng)求頭信息,Content-Type=application/x-www-form-urlencoded
print(res.request.headers)
print(res.text)
執(zhí)行結(jié)果:
{'User-Agent': 'python-requests/2.28.1', 'Accept-Encoding': 'gzip, deflate', 'Accept': '*/*', 'Connection': 'keep-alive', 'Content-Length': '50', 'Content-Type': 'application/x-www-form-urlencoded'}
{"msg":"登錄成功","code":0,"data":{"id":"22299","username":"xxxxx","nickname":"","mobile":"","email":"","avatar":"http:\/\/shop-xo.hctestedu.com\/static\/index\/default\/images\/default-user-avatar.jpg","alipay_openid":"","weixin_openid":"","weixin_unionid":"","weixin_web_openid":"","baidu_openid":"","toutiao_openid":"","qq_openid":"","qq_unionid":"","integral":"0","locking_integral":"0","referrer":"0","add_time":"1678005098","add_time_text":"2023-03-05 16:31:38","mobile_security":"","email_security":"","user_name_view":"xxxxx","is_mandatory_bind_mobile":0,"token":"d653d78ac417f65e1cd38c6f3e220341"}}
3、設(shè)置請(qǐng)求頭
如果是java項(xiàng)目,spring會(huì)將請(qǐng)求實(shí)體的內(nèi)容自動(dòng)轉(zhuǎn)換為Bean,但前提是請(qǐng)求的Content-Type必須設(shè)置為application/json
在請(qǐng)求頭中定義發(fā)送報(bào)文的格式
1、Content-Type: application/json
headers = {
'Content-Type': 'application/json'
# 'Content-Type': 'application/x-www-form-urlencoded'
}
url = 'http://shop-xo.hctestedu.com/index.php?s=api/user/login'
res = requests.post(url=url, params=param_data, json=data, headers=headers)
print(res.request.headers)
執(zhí)行結(jié)果:
{'User-Agent': 'python-requests/2.28.1', 'Accept-Encoding': 'gzip, deflate', 'Accept': '*/*', 'Connection': 'keep-alive', 'Content-Type': 'application/json', 'Content-Length': '50'}
2、Content-Type:application/x-www-form-urlencoded
headers = {
# 'Content-Type': 'application/json'
'Content-Type': 'application/x-www-form-urlencoded'
}
url = 'http://shop-xo.hctestedu.com/index.php?s=api/user/login'
res = requests.post(url=url, params=param_data, data=data, headers=headers)
print(res.request.headers)
執(zhí)行結(jié)果:
{'User-Agent': 'python-requests/2.28.1', 'Accept-Encoding': 'gzip, deflate', 'Accept': '*/*', 'Connection': 'keep-alive', 'Content-Type': 'application/x-www-form-urlencoded', 'Content-Length': '69'}
十一、Json和字典數(shù)據(jù)轉(zhuǎn)換
1、json.dumps(),將字典轉(zhuǎn)換成Json
使用json.dumps()可以將字典轉(zhuǎn)換成Json
test = {
"msg": "登錄成功",
"code": 0,
"data": {
"id": "22299",
"username": "Summer",
"nickname": "",
"mobile": "",
"email": "",
"avatar": "http:\/\/shop-xo.hctestedu.com\/static\/index\/default\/images\/default-user-avatar.jpg",
"alipay_openid": "",
"weixin_openid": "",
"weixin_unionid": "",
"weixin_web_openid": "",
"baidu_openid": "",
"toutiao_openid": "",
"qq_openid": "",
"qq_unionid": "",
"integral": "0",
"locking_integral": "0",
"referrer": "0",
"add_time": "1678005098",
"add_time_text": "2023-03-05 16:31:38",
"mobile_security": "",
"email_security": "",
"user_name_view": "chengcheng",
"is_mandatory_bind_mobile": 0,
"token": "d653d78ac417f65e1cd38c6f3e220341"
}
}
print(type(test))
print(json.dumps(test))
print(type(json.dumps(test)))
執(zhí)行結(jié)果:
<class 'dict'>
{"msg": "\u767b\u5f55\u6210\u529f", "code": 0, "data": {"id": "22299", "username": "Summer", "nickname": "", "mobile": "", "email": "", "avatar": "http:\\/\\/shop-xo.hctestedu.com\\/static\\/index\\/default\\/images\\/default-user-avatar.jpg", "alipay_openid": "", "weixin_openid": "", "weixin_unionid": "", "weixin_web_openid": "", "baidu_openid": "", "toutiao_openid": "", "qq_openid": "", "qq_unionid": "", "integral": "0", "locking_integral": "0", "referrer": "0", "add_time": "1678005098", "add_time_text": "2023-03-05 16:31:38", "mobile_security": "", "email_security": "", "user_name_view": "chengcheng", "is_mandatory_bind_mobile": 0, "token": "d653d78ac417f65e1cd38c6f3e220341"}}
<class 'str'>
2、json.loads(),將Json轉(zhuǎn)換成字典
使用json.loads()可以將Json轉(zhuǎn)換成字典
print(json.loads(json.dumps(test)))
print(type(json.loads(json.dumps(test))))
執(zhí)行結(jié)果:
{'msg': '登錄成功', 'code': 0, 'data': {'id': '22299', 'username': 'Summer', 'nickname': '', 'mobile': '', 'email': '', 'avatar': 'http:\\/\\/shop-xo.hctestedu.com\\/static\\/index\\/default\\/images\\/default-user-avatar.jpg', 'alipay_openid': '', 'weixin_openid': '', 'weixin_unionid': '', 'weixin_web_openid': '', 'baidu_openid': '', 'toutiao_openid': '', 'qq_openid': '', 'qq_unionid': '', 'integral': '0', 'locking_integral': '0', 'referrer': '0', 'add_time': '1678005098', 'add_time_text': '2023-03-05 16:31:38', 'mobile_security': '', 'email_security': '', 'user_name_view': 'chengcheng', 'is_mandatory_bind_mobile': 0, 'token': 'd653d78ac417f65e1cd38c6f3e220341'}}
<class 'dict'>
3、json格式報(bào)文發(fā)送
方法一:參數(shù)是data,值:將字典data轉(zhuǎn)換成json
url = 'http://shop-xo.hctestedu.com/index.php?s=api/user/login'
headers = {
'Content-Type': 'application/json'
}
res = requests.post(url=url, data=json.dumps(data), headers=headers)
print(res.text)
方法二:參數(shù)是json,值:字典data
url = 'http://shop-xo.hctestedu.com/index.php?s=api/user/login'
res = requests.post(url=url, json=data)
print(res.text)
print(res.json())
print(type(res.json()))
assert "登錄成功" == res.json()['msg']
十二、獲取接口響應(yīng)時(shí)間
url = 'http://shop-xo.hctestedu.com/index.php?s=api/user/login'
res = requests.post(url=url, json=data)
print(res.text)
# 獲取接口響應(yīng)時(shí)間,單位秒
print(r.elapsed.total_seconds())
執(zhí)行結(jié)果:
{"msg":"登錄成功","code":0,"data":{"body_html":""}}
0.078264
十三、接口調(diào)用失敗處理
同一個(gè)用例中有多個(gè)接口調(diào)用,一個(gè)接口調(diào)用失敗如何防止程序終止?
用于判斷接口請(qǐng)求的狀態(tài)碼是否為200,如果是,則返回none,如果不是則返回異常。
調(diào)用接口時(shí)結(jié)合try…except進(jìn)行使用。
# 模擬接口404,使用不存在的request url: login1
url = 'http://shop-xo.hctestedu.com/index.php?s=api/user/login1'
res = requests.post(url=url, json=data)
try:
assert 200 == res.status_code
except:
# 異常處理1:直接跳過,可繼續(xù)執(zhí)行后面代碼
# pass
# 異常處理2:打印詳細(xì)異常信息
print(res.status_code)
res.raise_for_status()
else:
print(res.text)
執(zhí)行結(jié)果:
404
Traceback (most recent call last):
File "E:\Coding\python-workspace\Interface_test\first_requests.py", line 220, in <module>
assert 200 == res.status_code
AssertionError
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "E:\Coding\python-workspace\Interface_test\first_requests.py", line 226, in <module>
res.raise_for_status()
File "D:\Developer\Python\Python310\lib\site-packages\requests\models.py", line 1021, in raise_for_status
raise HTTPError(http_error_msg, response=self)
requests.exceptions.HTTPError: 404 Client Error: Not Found for url: http://shop-xo.hctestedu.com/index.php?s=api/user/login1
十四、接口超時(shí)
url = 'http://shop-xo.hctestedu.com/index.php?s=api/user/login'
try:
res = requests.post(url=url, json=data, timeout=0.01) # timeout,單位秒
except (TimeoutError, ReadTimeout, ConnectTimeout):
# ConnectTimeout:指的是建立連接所用的時(shí)間,適用于網(wǎng)絡(luò)狀況正常的情況下,兩端連接所用的時(shí)間。
# ReadTimeout:指的是建立連接后從服務(wù)器讀取到可用資源所用的時(shí)間。
print("發(fā)生錯(cuò)誤,請(qǐng)稍后重試")
else:
# 獲取接口響應(yīng)時(shí)間,單位秒
print(res.elapsed.total_seconds())
print(res.text)
執(zhí)行結(jié)果:文章來源:http://www.zghlxwxcb.cn/news/detail-423558.html
發(fā)生錯(cuò)誤,請(qǐng)稍后重試
當(dāng)把timeout改成0.1,執(zhí)行結(jié)果:文章來源地址http://www.zghlxwxcb.cn/news/detail-423558.html
0.07419
{"msg":"登錄成功","code":0,"data":{"body_html":""}}
到了這里,關(guān)于Python發(fā)送Post請(qǐng)求及解析響應(yīng)結(jié)果的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!