Python中,系统自带的urllib和urllib2都提供了功能强大的HTTP支持,但是API接口确实太难用了。Requests 作为更高一层的封装,在大部分情况下对得起它的slogan——HTTP for Humans。
让我们一起来看看 Requests 这个 HTTP库在我们接口自动化测试中的使用吧
发送请求
在使用 Requests发送网络请求非常简单,经常使用一两行代码就可以搞定。
Requests是一个第三方库,在使用它之前需要先安装这个库:
pip install requests
发送GET请求示例:
import requests
# 发送GET请求,获取所有项目信息
response = requests.get("http://127.0.0.1:8000/api/projects/")
# 传递 URL 参数
params = {'id': 1, 'name': 'project_01'}
response = requests.get("http://127.0.0.1:8000/api/projects/", params= params)
响应数据的获取也非常简单明了。
示例:
# 获取状态码
print(response.status_code)
# 获取头信息或者指定头信息
print(response.headers)
print(response.headers["Content-Type"])
# 获取cookie
print(response.cookies)
# 获取响应正文
body = response.text
print(body)
# 使用内置的 JSON 解码器,处理 JSON 数据
jsonBody = response.json()
print(jsonBody)
print(jsonBody[0]["name"])
Requests 会自动解码来自服务器的内容。大多数 unicode 字符集都能被无缝地解码。请求发出后,Requests 会基于 HTTP 头部对响应的编码作出有根据的推测。当访问应答正文时,,Requests 会使用其推测的文本编码。你可以找出 Requests 使用了什么编码,并且能够使用 response.encoding 属性来改变它。
发送POST请求示例:
project = {"name": "project_001", "version": "2.0", "type": "App",
"status": False,"description": "this is another test project",
"createUser": 1}
response = requests.post("http://127.0.0.1:8000/api/projects/", project)
重定向、
超时和代理
Requests 之所以称为“HTTP for human”,因为其封装层次很高,其中一处体现就在:Requests会自动处理服务器响应的重定向。
response = session.get("http://10.0.0.11:8000/login/", allow_redirects=False)
注:
allow_redirects参数为False则表示不会主动重定向。
有时候对方网站的响应时间太长了,我们希望在指定时间内完事,或者直接停止这个请求。示例:
response = session.get("http://10.0.0.11:8000/login/", timeout=3)
注:
timeout表示这次请求最长只等待多少秒,超过设置的时间后报错。
为了防止反爬虫之类机制,Requests 套上一层代理的做法也非常简单:
proxies = {
"http": "http://192.168.31.1:3128",
"https": "http://10.10.1.10:1080",
}
response = session.get("http://10.0.0.11:8000/login/", proxies=proxies)
会话对象
会话对象能够跨请求保持某些参数。它也会在同一个 Session 实例发出的所有请求之间保持 cookie, 期间使用 urllib3 的 connection pooling 功能。所以如果向同一主机发送多个请求,底层的 TCP 连接将会被重用,从而带来显著的性能提升。
我们以 Django Web 应用的登录请求操作,需要前面一个GET请求中的csrf_token值为例:
session = requests.Session()
getResponse = session.get("http://10.0.0.11:8000/login/")
pattern = 'input type="hidden" name="csrfmiddlewaretoken" value="(.+?)"'
token = re.findall(pattern, getResponse.text)
print(token)
data = {
"username": "testops",
"password": "test123456",
"csrfmiddlewaretoken": token
}
postResponse = session.post("http://10.0.0.11:8000/login_action/", data)
后记
当然 Requests 的功能不止这么一些,我们使用 Requests 作为基于 HTTP 协议的接口自动化测试还需要学习的内容也很多,大家可以参考官方文档进行更多的学习:
https://requests.readthedocs.io/en/master/
微信号 : TestOps
知乎:@TestOps云层