python 接口测试 request 模块的学习记录

一、安装 requests

pip install requests

二、内置请求方法:

request 方法参数具体有哪些:

url:请求的URL地址。
params:请求的查询参数,可以是一个字典或字符串。
headers:请求的头部信息,可以是一个字典。
data:请求的主体数据,可以是一个字典、字符串或文件对象。
json:请求的主体数据,以JSON格式发送。
cookies:请求的Cookie信息,可以是一个字典。
auth:请求的身份验证信息,可以是一个元组。
timeout:请求的超时时间,可以是一个整数或浮点数。
proxies:请求的代理信息,可以是一个字典。
verify:请求的SSL证书验证方式,可以是一个布尔值或字符串。
allow_redirects:请求的重定向方式,可以是一个布尔值或字符串。


requests.get()
    headers = {
    
    }
	access_token = {
    
    'access_token': response.json()['access_token']}
	response = requests.get(url = url, headers=headers, params = access_token ) 
	# url是接口地址 params 传参,例如 access_token
	

requests.post()  
	response = requests.post(url = url, data=data) 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  二进制文件的格式

data和json传参  和content_type的关系如下:

1、data传参:报文是dict类型,默认content_type:application/x-www-form-urlencoded     
表单  纯健值对的格式,如下所示:(这个比较上传表单数据时常用)
{
    
    
	"test1": "测试数据1",
	"test2": "测试数据2",
}

data传参:报文是str类型:默认 content_type:text/plain  字符串

2、json 传参:报文可以是dict,默认是 content_type:application/json

(上传复制数据时常用)
{
    
    
'data':{
    
    
	"row":{
    
    
			'id':1,
			'name':'y'
   		  }
 	  }		
}
当你看到嵌套的字典的时候 ,直接用 json 来传参,上面的数据类型,就需要 json 传参
当你看到是健值对的格式的时候,用 data 来传参 

如果想转换数据格式可以用:
json.loads()    把json字符串转换成字典格式
json.dumps()   把字典格式转换成json字符串

如果你不知道用data还是用json,可以用一个抓包工具去抓取,看content_type,决定用哪种方式去传参。

requests.put()
requests.delete()
###########################################################################
requests.request()  可以发送 get 请求,也可以发送post请求,实际工作中经常用的是这个
###########################################################################
不管是 get 还是 post、put、delete 等请求方法,调用的都是requests.request 方法,
而requests.request调用的是session。
############################################################################
request  方法参数详解:

method		请求方式 get、post,大小写都可以
url		接口路径
params = none  get请求参数
data = none  post 请求包内携带的数据,post请求参数
json       post请求
headers = none  请求头
cookies  = none  请求cookie
files = none  文件上传

三、响应 response 方法:

response:

response.json() 获取返回的字典格式的数据
response.text()  返回字符串格式的数据
response.content()  返回byte 字节类型的数据
response.status_code  返回状态码
response.reason() 返回状态信息
response.cookies 返回cookie 信息
response.headers()  返回响应头
response.encoding 查看响应头部字符编码

请求必须带请求头的接口,以及需要cookie鉴权和session鉴权


参考链接

接口测试 requests 库 以及response 返回对象

python——Request模块

Python用GET方法上传文件

猜你喜欢

转载自blog.csdn.net/qq_42701659/article/details/132875681
今日推荐