您的位置:首页 > 编程语言 > Python开发

使用Python的requests库作接口测试——请求对象与响应对象

2017-09-19 09:29 423 查看
任何时候调用requests.*()操作接口时,我们都在做两件事情:

1、构建一个Request对象,该对象被发送到服务器去请求或查询一些资源;

2、一旦requests得到一个从服务器返回的响应,就有产生一个Response对象,该对象包含从服务器返回的所有信息,也包含你原来创建的Request对象。

举个栗子:

从Wikipedia的服务器得到一些信息:

>>> r = requests.get('http://en.wikipedia.org/wiki/Monty_Python')

如果想访问服务器返回给我们的响应头部信息,可以这样做:

>>> r.headers

结果是:

{'content-length': '68770', 'x-varnish': '1501359345 1500157800, 2078355484, 432
596611', 'x-analytics': 'page_id=18942;ns=0;https=1;WMF-Last-Access=31-Aug-2015'
, 'content-language': 'en', 'x-content-type-options': 'nosniff', 'x-powered-by':
'HHVM/3.6.5', 'x-cache': 'cp1053 hit (2), cp4016 miss (0), cp4010 frontend miss
(0)', 'accept-ranges': 'bytes', 'content-encoding': 'gzip', 'vary': 'Accept-Enc
oding,Cookie', 'server': 'nginx/1.9.3', 'last-modified': 'Mon, 31 Aug 2015 05:31
:38 GMT', 'connection': 'keep-alive', 'via': '1.1 varnish, 1.1 varnish, 1.1 varn
ish', 'strict-transport-security': 'max-age=31536000; includeSubDomains; preload
', 'x-ua-compatible': 'IE=Edge', 'cache-control': 'private, s-maxage=0, max-age=
0, must-revalidate', 'date': 'Mon, 31 Aug 2015 05:44:17 GMT', 'content-type': 't
ext/html; charset=UTF-8', 'age': '698'}

如果想要得到发送到服务器的请求头部,可以这样:

>>> r.request.headers

结果是这样:

{'Connection': 'keep-alive', 'Cookie': 'GeoIP=CN:22:Beijing:39.9289:116.3883:v4;
WMF-Last-Access=31-Aug-2015', 'Accept-Encoding': 'gzip, deflate', 'Accept': '*/
*', 'User-Agent': 'python-requests/2.6.0 CPython/2.7.10 Windows/7'}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: