文未有福利 | BAT 名企大厂做接口自动化如何高效使用 Requests ?

116 阅读4分钟

获取更多技术文章分享 Requests是一个优雅而简单的python HTTP库,其实python内置了用于访问网络的资源模块,比如urllib,但是它不如requests简单,优雅,而且缺少许多实用功能。接下来的接口测试的学习和实战,都与requests库息息相关。

Requests官方文档:2.python-requests.org/en/master/ 接下来就会使用最流行的requests进行接口测试

requests提供了几乎所有的HTTP请求构造方法,以及通过传入参数的方法,对发送的请求进行定制化的配置。可以用来应对各种不同的请求场景。 pip命令安装requests。

pip install requests

发送get请求

import requestsr = requests.get('https://api.github.com/events')

在请求中添加data参数,并发送post请求

import requestsr = requests.post('http://httpbin.org/post', data = {'key':'value'})

在请求中添加data参数,并发送put请求

import requestsr = requests.put('http://httpbin.org/put', data = {'key':'value'})

发送delete请求

import requestsr = requests.delete('http://httpbin.org/delete')

发送head请求

mport requestsr = requests.head('http://httpbin.org/get')

发送options请求

import requestsr = requests.options('http://httpbin.org/get')

也可以直接使用request函数,传入不同的method,例如使用这个方法发送get请求

import requestsrequests.request("get", "http://www.baidu.com")

下面的参数都是非必须参数,但是如果需要对请求做额外的定制化,则需要以下这些参数的作用。

  • header参数,通过传入dict定制请求头
import requests
url = 'https://api.github.com/some/endpoint'
headers = {'user-agent': 'my-app/0.0.1'}
r = requests.get(url, headers=headers)

  • data参数发送编码为表单形式的数据单
>>> payload = {'key1': 'value1', 'key2': 'value2'}
>>> r = requests.post("http://httpbin.org/post", data=payload)
>>> print(r.text)

{
  ...
    "form": {
        "key2": "value2",
            "key1": "value1"
              },
                ...
                }
                
                ```
                
                
                - files参数,上传文件,dict格式。
                ```
                >>> url = 'http://httpbin.org/post'
                >>> files = {'file': open('report.xls', 'rb')}
                >>> r = requests.post(url, files=files)
                >>> r.text
                
                {
                  ...
                    "files": {
                        "file": "<censored...binary...data>"
                          },
                            ...
                            }
                            
                            ```
                            
                            
                            注意:建议用二进制模式(binary mode)打开文件。这是因为 Requests 可能会试图为你提供 Content-Length header,在它这样做的时候,这个值会被设为文件的字节数(bytes)。如果用文本模式(text mode)打开文件,就可能会发生错误。
                            
                            - timeout参数设定超时时间(秒),到达这个时间之后会停止等待响应:
                            ```
                            >>> requests.get('http://github.com', timeout=0.001)
                            
                            Traceback (most recent call last):
                              File "<stdin>", line 1, in <module>
                              requests.exceptions.Timeout:\
                               HTTPConnectionPool(host='github.com', port=80):\
                                 Request timed out. (timeout=0.001)
                                 
                                 
                                 ```
                                 
                                 
                                 注意:timeout 仅对连接过程有效,与响应体的下载无关。 timeout 并不是整个下载响应的时间限制,而是如果服务器在 timeout 秒内没有应答,将会引发一个异常(更精确地说,是在 timeout 秒内没有从基础套接字上接收到任何字节的数据时),如果不设置 timeout,将一直等待。
                                 
                                 - allow_redirects参数
                                 控制是否启用重定向,bool类型,选择True为启用,选择False为禁用
                                 ```
                                 import requests
                                 >>> r = requests.get('http://github.com', allow_redirects=False)
                                 >>> r.status_code
                                 
                                 301
                                 
                                 ```
                                 
                                 
                                 - proxies参数
                                 设置代理,dict格式,key值为选择的协议,可以分别设置http请求和https请求的代理。
                                 ```
                                 import requests
                                 
                                 proxies = {
                                   'http': 'http://10.10.1.10:3128',
                                     'https': 'http://10.10.1.10:1080',
                                     }
                                     
                                     requests.get('https://api.github.com/events', proxies=proxies)
                                     
                                     ```
                                     
                                     
                                     - verify参数可以传入bool值或者string,默认为True。
                                     
                                     如果设置为False的即为忽略对SSL证书的验证;反之就是需要做验证;如果传入值为string的话,代表指定本地的证书作为客户端证书。
                                      
                                      - 从本地传入证书
                                      ```
                                      import requests>>> requests.get('https://github.com', verify='/path/to/certfile')
                                      
                                      ```
                                      
                                      
                                      - 忽略对SSL证书的验证
                                      ```
                                      import requests>>> requests.get('https://kennethreitz.org', verify=False)
                                      
                                      ```
                                      
                                      
                                      另外三个重要参数json、cookies、auth则会在后面的章节进行详细的介绍。
                                      
                                      
                                      ## 
                                      接口请求断言是指在发起请求之后,对返回的响应内容去做判断,用来查看是否响应内容是否与规定的返回值相符。
                                      
                                      
                                      在发起请求后,我们使用一个变量r存储响应的内容,也就是Response对象。
                                      ```
                                      >>> import requests
                                      >>> r = requests.get('http://httpbin.org/get')
                                      >>> print(r)
                                      <Response [200]>
                                      >>> import requests
                                      >>> r = requests.get('http://httpbin.org/get')
                                      >>> print(r)
                                      <Response [200]>
                                      
                                      ```
                                      
                                      
                                      Response对象有很多功能强大的方法可以调用,比如直接获取响应头,获取Unicode编码后的响应内容,获取二进制的响应内容,获取原始的响应内容等等。
                                      
                                      - 获得响应头
                                      ```
                                      >>> r.headers
                                      {'Date': 'Sun, 05 Apr 2020 16:38:09 GMT', \
                                      'Content-Type': 'application/json', \
                                      'Content-Length': '308', 'Connection': 'keep-alive',\
                                       'Server': 'gunicorn/19.9.0', \
                                        'Access-Control-Allow-Origin': '*', \
                                         'Access-Control-Allow-Credentials': 'true'}
                                         
                                         ```
                                         
                                         
                                         - 获得编码后的响应值
                                         ```
                                         >>> print(r.text)
                                         {
                                           "args": {}, 
                                             "data": "", 
                                               "files": {}, 
                                                 "form": {
                                                     "hogwarts": [
                                                           "a", 
                                                                 "b", 
                                                                       "c"
                                                                           ]
                                                                             }, 
                                                                               "headers": {
                                                                                   "Accept": "*/*", 
                                                                                       "Accept-Encoding": "gzip, deflate", 
                                                                                           "Content-Length": "32", 
                                                                                               "Content-Type": "application/x-www-form-urlencoded", 
                                                                                                   "Host": "httpbin.org", 
                                                                                                       "User-Agent": "python-requests/2.22.0", 
                                                                                                           "X-Amzn-Trace-Id": "Root=1-5e8a01e3-0913fca09ac605ccc911ccde"
                                                                                                             }, 
                                                                                                               "json": null, 
                                                                                                                 "origin": "113.118.101.232", 
                                                                                                                   "url": "http://httpbin.org/post"
                                                                                                                   }
                                                                                                                   
                                                                                                                   ```
                                                                                                                   
                                                                                                                   
                                                                                                                   还可以使用r.raw获得原始响应内容,r.content获得二进制的响应内容,另外还有编码为json格式的响应内容,会在后面的章节进行详述。
                                                                                                                   
                                                                                                                   本周霍格沃兹测试学院测试公开课,@飞儿 @AD 老师 将在16日、17日连续两天带你快速掌握“最火的 Requests 库使用 +  接口测试实战技能 + 最流行的 Allure 测试报告框架”,助你实现职场进阶。
                                                                                                                   立即扫码报名,锁定听课名额!点击「阅读原文」可查看课前准备
                                                                                                                   [原文链接](https://mp.weixin.qq.com/s?__biz=MzU3NDM4ODEzMg==&mid=2247493530&idx=1&sn=d963d309a8bccac17df604638b9c2111&chksm=fd318551ca460c470f59594a8e648e7edc71f90183d81abe1b756dd63d83f3f1e9ea2ec413d1#rd) 
                                                                                                                   
                                                                                                                   
                                                                                                                   
                                                                                                                   [获取更多技术文章分享](https://qrcode.ceba.ceshiren.com/link?name=article&project_id=qrcode&from=juejin&timestamp=1650446169
                                                                                                                   ) ![img](https://qrcode.ceba.ceshiren.com/link?name=article&project_id=qrcode&from=juejin&timestamp=1650446169)