Wen Wei has no benefits | How to use Requests efficiently when BAT famous enterprises do interface automation?


Requests is an elegant and simple python HTTP library. In fact, python has built-in resource modules for accessing the network, such as urllib, but it is not as simple and elegant as requests, and it lacks many practical functions. The learning and actual combat of the following interface tests are closely related to the requests library.

Requests official documentation: https://2.python-requests.org/en/master/ Next, the most popular requests will be used for interface testing

Requests provides almost all HTTP request construction methods, as well as the method of passing in parameters to customize the configuration of the sent requests. Can be used to deal with a variety of different request scenarios.
The pip command installs requests.

pip install requests

send get request

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

Add the data parameter to the request and send a post request

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

Add the data parameter to the request and send a put request

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

send delete request

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

send head request

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

send options request

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

You can also use the request function directly to pass in different methods, for example, use this method to send a get request

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

The following parameters are all optional parameters, but if additional customization is required for the request, the following parameters are required.

  • Header parameter, custom request header by passing in dict
import requests
url = 'https://api.github.com/some/endpoint'
headers = {'user-agent': 'my-app/0.0.1'}
r = requests.get(url, headers=headers)

  • The data parameter sends a data sheet encoded as a form
  • 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>"
          },
            ...
            }

Note: It is recommended to open the file in binary mode. This is because Requests may try to provide you with a Content-Length header, and when it does so, this value will be set to the number of bytes in the file. An error may occur if the file is opened in text mode.

  • The timeout parameter sets the timeout time (seconds), after which it will stop waiting for a response:
  • requests.get(‘http://github.com’, timeout=0.001)
    Traceback (most recent call last):
    File “”, line 1, in
    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 parameter
  • Set proxy, dict format, key value is the selected protocol, you can set proxy for http request and https request respectively.
  • 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')
  • Ignore verification of SSL certificate
  • import requests>>> requests.get(‘https://kennethreitz.org’, verify=False)


另外三个重要参数json、cookies、auth则会在后面的章节进行详细的介绍。


## 
接口请求断言是指在发起请求之后,对返回的响应内容去做判断,用来查看是否响应内容是否与规定的返回值相符。


在发起请求后,我们使用一个变量r存储响应的内容,也就是Response对象。

import requests

r = requests.get(‘http://httpbin.org/get’)
print®
<Response [200]>
import requests
r = requests.get(‘http://httpbin.org/get’)
print®
<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'}
  • Get the encoded response value
  • 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=bokeyuan&timestamp=1650434543)

Guess you like

Origin blog.csdn.net/hogwarts_2022/article/details/124296147