这篇文章主要讲解了Python request的用法,内容清晰明了,对此有兴趣的小伙伴可以学习一下,相信大家阅读完之后会有帮助。
操作步骤
A.cmd输入:pip install requests,安装requests
B.py文件导入:import requests
C.get
D.post
入参为json格式需要把字典转成json格式: json_data =json.dumps({"usename": "test","password" : "123456"}) ,
请求报头为json格式:self.json_headers= {'content-type': 'application/json'}
调用post(请求与返回都是josn格式):
r = requests.post(url,data=json_data,headers=self.json_headers)
如果返回内容为:[{'name': 'zhangshan', 'age': '18'}, {'name': 'lisi', 'age': '29'}]
断言1:self.assertEqual(r.json()[0]['name'], 'zhangshan') ,说明r.json()转成list,list里面是字典,取list[0]第一个值,取字典key值['name']
如果返回内容:{'success': 'true', 'msg': 'chengong'}
断言2:self.assertEqual(r.json()['success'], 'true'),说明r.json()转成字典,取字典key值['success']
config.json 配置文件内容:
[ { "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 返回值文件内容:
[ { "name": "zhangshan", "age": "18" }, { "name": "lisi", "age": "29" } ]
user.json 入参文件内容:
{ "usename": "test", "password" : "123456" }
python文件“login.py”内容:
#!/usr/bin/python3 # encoding:utf-8 import unittest import requests import json class 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 + path if __name__=='__main__': unittest.main()
运行结果
.2
...
.----------------------------------------------------------------------
.Ran 3 tests in 0.036s
.
.OK
看完上述内容,是不是对Python request的用法有进一步的了解,如果还想学习更多内容,欢迎关注亿速云行业资讯频道。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。