requests是用来发送http请求以及接受http响应的的python的第三方库,主要用于借口自动化测试
pip install requests
requests方法:
requests.get()
res = requests.get(url = url,params = data) url是接口地址 params 传参
requests.post()
res = requests.post(url = url,) url是接口地址 data传参 json 传参
data 和json传参的区别:通过请求头content_type区分
请求分为四个部分:请求头 请求方式 请求路径 请求正文
content_type:服务器要求传入的报文的内容类型
postman post请求 4种传参方式 对应的content_type的值如下:
1,from_data:content_tyep:multipart/from-data 文件上传
2,x-www_form_urlencoded:content_type: application/x-www-form-urlencoded 表单提交
3,raw:
Text:content_type:text/plain
Json:content_type:application/json
javascript:content_type:application/javascript
xml:text/html
html:content_type:application/html
4,bianry:content_type:application/bianry 二进制文件的格式
datag和json传参 和content_type的关系如下:
1,data传参:报文是dict类型,默认content_type:application/x-www-form-urlencoded 表单 纯健值对的格式
data传参:报文是str类型:默认content_type:text/plain 字符串
2,json 传参:报文可以是dict,默认是content_type:application/json {'data':{
"row":{
'id':1,
'name':'y'
}
}}
当你看到嵌套的字典的时候 ,直接用json来传参
当你看到是健值对的格式的时候,用data来传参
如果想转换数据格式可以用:
json.loads() 把json字符串转换成字典格式
json.dumps() 把字典格式转换成json字符串
如果你不知道用data还是用json,可以用一个抓包工具去抓取,看content_type,决定用哪种方式去传参。
requests.put()
requests.delete()
requests.request() 可以发送 get 请求,也可以发送post请求,实际工作中经常用的是这个
不管是get 还是post put deleter 调用的都是requests.request 方法,而requests.request调用的是session。request 方法
method 请求方式
url 路径
params = none get请求
data = none post 请求
json post请求
headers = none 请求头
cookies = none 请求cookie
files = none 文件上传
response:
res.json() 获取返回的字典格式的数据
res.text() 返回字符串格式的数据
res.content() 返回byte 字节类型的数据
res.status_code 返回状态码
res.reason() 返回状态信息
res.cookies 返回cookie 信息
res.headers() 返回响应头
请求必须带请求头的接口,以及需要cookie鉴权和session鉴权