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

任何时候调用requests.*()操作接口时,我们都在做两件事情:

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

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

举个栗子:

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

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

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

  1. >>> 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'}

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

 
  1. >>> 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'}

原文地址:https://www.cnblogs.com/dancesir/p/7550081.html