Python request操作步驟及代碼實(shí)例
操作步驟
A.cmd輸入:pip install requests,安裝requests
B.py文件導(dǎo)入:import requests
C.get
調(diào)用get: r = requests.get(url) 斷言:self.assertEqual(r.status_code, 200) 說明:status_code為狀態(tài)返回值,如200表示訪問成功D.post
入?yún)閖son格式需要把字典轉(zhuǎn)成json格式: json_data =json.dumps({'usename': 'test','password' : '123456'}) ,
請求報頭為json格式:self.json_headers= {’content-type’: ’application/json’}
調(diào)用post(請求與返回都是josn格式):
r = requests.post(url,data=json_data,headers=self.json_headers)
如果返回內(nèi)容為:[{’name’: ’zhangshan’, ’age’: ’18’}, {’name’: ’lisi’, ’age’: ’29’}]
斷言1:self.assertEqual(r.json()[0][’name’], ’zhangshan’) ,說明r.json()轉(zhuǎn)成list,list里面是字典,取list[0]第一個值,取字典key值[’name’]
如果返回內(nèi)容:{’success’: ’true’, ’msg’: ’chengong’}
斷言2:self.assertEqual(r.json()[’success’], ’true’),說明r.json()轉(zhuǎn)成字典,取字典key值[’success’]
config.json 配置文件內(nèi)容:
[ { 'request' : { 'method': 'post', 'uri' : '/login', 'file': { 'json': 'user.json' } }, 'response' : { 'json': {'success': 'true','msg': 'chengong'} } }, { 'request' : { 'method': 'post', 'uri' : '/data' }, 'response' : { 'file' : 'data.json' } }, { 'request' : { 'method': 'get', 'uri' : '/home' }, 'response' : { 'text' : { 'template': 'true' } } }]
data.json 返回值文件內(nèi)容:
[ { 'name': 'zhangshan', 'age': '18' }, { 'name': 'lisi', 'age': '29' }]
user.json 入?yún)⑽募?nèi)容:
{'usename': 'test','password' : '123456'}
python文件“l(fā)ogin.py”內(nèi)容:
#!/usr/bin/python3# encoding:utf-8import unittestimport requestsimport jsonclass login(unittest.TestCase): def setUp(self): self.d =’http://127.0.0.1:9999’ self.json_headers= {’content-type’: ’application/json’} def tearDown(self): pass def test_gethome(self): url = self.url(’/home’)#http://127.0.0.1:9999/home r = requests.get(url) self.assertEqual(r.text, ’true’) self.assertEqual(r.status_code, 200) def test_postlogin(self): url= self.url(’/login’) json_data =json.dumps({'usename': 'test','password' : '123456'}) r = requests.post(url,data=json_data,headers=self.json_headers) #{’success’: ’true’, ’msg’: ’chengong’} self.assertEqual(r.json()[’success’], ’true’) def test_postdata(self): url= self.url(’/data’) r = requests.post(url,data={},headers=self.json_headers) print(len(r.json()))#r.josn返回list,長度2 #[{’name’: ’zhangshan’, ’age’: ’18’}, {’name’: ’lisi’, ’age’: ’29’}] self.assertEqual(r.json()[0][’name’], ’zhangshan’) self.assertEqual(r.json()[-1][’age’],’29’) def url(self,path): return self.d + pathif __name__==’__main__’: unittest.main()
運(yùn)行結(jié)果
.2....----------------------------------------------------------------------.Ran 3 tests in 0.036s..OK
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. HTML中的XML數(shù)據(jù)島記錄編輯與添加2. 三個不常見的 HTML5 實(shí)用新特性簡介3. 淺談CSS不規(guī)則邊框的生成方案4. html中的form不提交(排除)某些input 原創(chuàng)5. asp在iis7報錯行號不準(zhǔn)問題的解決方法6. msxml3.dll 錯誤 800c0019 系統(tǒng)錯誤:-2146697191解決方法7. CSS可以做的幾個令你嘆為觀止的實(shí)例分享8. 詳解盒子端CSS動畫性能提升9. 基于HTTP瀏覽器緩存機(jī)制全面解析10. CSS百分比padding制作圖片自適應(yīng)布局
