Detailed explanation of the -requests module of interface automation testing

1. Background of requests

Requests inherits all the features of urllib2. Requests supports HTTP connection retention and connection pooling, supports the use of cookies to maintain sessions, supports file uploading, supports automatic determination of the response content encoding, and supports internationalized URL and POST data automatic encoding.

Second, requests installation

Install with pip:
$ pip install requests

3. Use of requests

GET request

1. Basic GET request

response = requests.get("http://www.baidu.com/")
#也可以这样写
response = requests.request("get","http://www.baidu.com/")

2. Add headers and params

If you want to add headers, you can pass in the headers parameter to increase the header information in the request header. If you want to pass the parameters in the url, you can use the params parameter.

key = {'key': 'CC'}
headers = {
    "User-Agent": "Mozilla/5.0"}
response = requests.get("http://www.baidu.com/s?", params=key, headers=headers)
print(response.text)# 查看响应内容,response.text 返回的是Unicode格式的数据
print(response.content)# 查看响应内容,response.content返回的字节流数据
print(response.status_code)# 查看响应码

If you want to fetch text, you can use response.text; if you want to fetch pictures / files, you can use response.content.

POST method

1. Basic POST request

response = requests.post("http://www.baidu.com/",data = data)

2.body with parameters

formdata = {
    "type": "AUTO",
    "doctype": "json",
    "key": "www",
    "ue": "UTF-8",
}
url = "http://auto-installment/v1/loan-credit-check"
response = requests.post(url,data = data,headers=headers)

print(response.text)#显示返回结果
print(response.json())# 如果是json文件可以直接显示

Note: The
printed result appears garbled in Chinese, use json.dupms (response, ensure_ascii = False)) to solve

Session

Generally use Session to maintain certain parameters during cross-requests, such as access to other pages after login

# 1. 创建session对象,可以保存Cookie值
session = requests.session()

# 2. 需要登录的用户名和密码
data = {"username": "mxxxx", "password": "1233444"}

# 3. 发送附带用户名和密码的请求,并获取登录后的Cookie值,保存在ssion里
session.post("https://www.jianshu.com/sign_in", data=data)

# 4. ssion包含用户登录后的Cookie值,可以直接访问那些登录后才可以访问的页面
response = session.get("https://www.jianshu.com/writer#/")

Precautions:

1. When using requests to request an interface, an error occurs, but the interface itself is not a problem. This is because the request parameters of the interface have two cases: simple types (generally less than 3) and complex object types.

Solution: Define the
simple types of these two parameters in headers: headers = {"Content-Type": "application / x-www-form-urlencoded"}
complex object types: headers = {"Content-Type" : application / json}
2. Some HTTPS requests have SSL certificate verification
solutions: response = requests.get (" https://www.baidu.com/ ", verify = False)

Four, requests expansion

1. After the request fails, add a retry mechanism (if it fails, it will be retried 3 times)

request_retry = requests.adapatrs.HTTPAdapaters(max_retries=3)
session.mount('https://',request_retry)  

2. Use grequests to implement asynchronous requests

urls = [
    'http://www.url1.com',
    'http://www.url2.com',
    'http://www.url3.com',
    'http://www.url4.com',
    'http://www.url5.com',
]
resp = (grequests.get(u) for u in urls)
grequests.map(resp)

3. Custom cookies

We use Session instances to maintain cookies between requests, but in some special cases, you need to use custom cookies

我们使用Session实例来保持请求之间的cookies,但是有些特殊情况,需要使用自定义的cookies
# 自定义cookies
cookie = {'guid':'5BF0FAB4-A7CF-463E-8C17-C1576fc7a9a8','uuid':'3ff5f4091f35a467'}

session.post('http://', cookies=cookie)

4. Count the time taken by an API request

session.get(url).elapsed.total_seconds() 

5. Set the request timeout

session.get(url, timeout=15)

6. File upload

Requests uses files as parameters to simulate submitting file data

file = {'file':open('test.bmp','rb')}   #rb表示用二进制格式打开指定目录下的文件,且用于只读
r =requests.post('http://',files=file)
print(r.text)

V. Summary

If you think this article is helpful to you, if you are interested in software testing, interface testing, automated testing, interview experience exchange, please join:

Software testing technology group: 695458161, the free materials distributed in the group are the essence of the author's more than ten years of testing career. There are also peers to exchange technology together.

Author: Zhuge
Source: https: //www.cnblogs.com/csmashang/p/12713012.html
original is not easy, welcome to reprint, but without the author's consent Keep declared by this section, given the original article page link in the apparent position.

Guess you like

Origin www.cnblogs.com/csmashang/p/12713012.html