requests模块
1、介绍
-
定义
非常优秀的第三方请求模块,支持多种HTTP请求方式,
在开发中经常用来做单元测试;
在数据获取中经常用来做爬虫。
-
安装
pip install requests
-
常用方法
- requests.get(url=“http://www.baidu.com/”, headers={})
- requests.post(url=“URL地址”, json={} , headers={})
- requests.put(url=“URL地址”, json={}, headers={})
- requests.delete(url=“URL地址”, json={}, headers={})
-
参数
- url : 请求URL地址
- json = {} :请求体数据,request.body ----> {“username”: xxx, “password”: xxx}
- data = {} :请求体数据,request.body ----> “username=xxx&password=xxx”
- headers = {} :请求头 {“authorization”: “xxxxxxx”}
-
响应对象的属性
- resp.text :获取响应内容 - 字符串
- resp.json() :获取响应内容,自动将json格式的字符串转为python对象【等价于json.loads()】
- resp.content :获取响应内容 - 字节串
- resp.status_code :http响应码
-
示例
-
POST测试登录功能
"""测试达达商城登录功能请求地址:http://127.0.0.1:8000/v1/tokens请求方式:POST请求体: {"username":xxx, "password":xxx, "carts":xx} """import requestsurl = "http://127.0.0.1:8000/v1/tokens" data = {"username": "zhaoliying","password": "123456","carts": 0 }resp = requests.post(url=url, json=data)print(resp.json())
-
GET测试地址查询功能
import requestsurl = "http://127.0.0.1:8000/v1/users/zhaoliying/address" headers = {"authorization": "自己的token", }html = requests.get(url=url, headers=headers).json() print(html)
-
DELETE请求测试地址删除功能
import requestsurl = "http://127.0.0.1:8000/v1/users/zhaoliying/address/3" data = {"id": "3"} headers = {"authorization": "自己的token", }html = requests.delete(url=url, json=data, headers=headers).json() print(html)
-