接着上一篇继续分享
上一篇测试数据的结构增加了headers,对于headers处理,主要区别Content-Type的处理。比较常见的是Content-Type:application/json和Content-Type:multipart/form-data这两种。这次封装的改动主要是针对后者。
改动后的代码如下:
#!/usr/bin/python
# -*- coding: utf-8 -*-
import requests
from requests.packages.urllib3.exceptions import InsecureRequestWarning
from requests_toolbelt import MultipartEncoder
from common.logger import logger
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
def request_handler(method: str, url: str, headers: dict, data: dict):
"""
:param headers: 请求头
:param method: 方法字符串,'GET','POST'
:param url: 请求地址
:param data: 要传递的参数
:return: 返回响应的数据
"""
try:
method = method.upper()
if method == "GET" or method == "DELETE":
return requests.request(method=method, url=url, params=data, verify=False).json()
elif method == "POST" or method == "PUT":
if 'form-data ' in headers['Content-Type']:
m = MultipartEncoder(
fields=data
)
headers['Content-Type'] = m.content_type
return requests.request(method=method, url=url, headers=headers, data=m, verify=False).json()
else:
return requests.request(method=method, url=url, headers=headers, json=data, verify=False).json()
else:
logger.debug(f"=====大兄弟===暂不支持{method}呢====你快点补充吧====")
return None
except Exception as e:
raise e
上面增加了multipart/form-data表单提交的情况,需要requests_toolbelt这个库,还是通过pip命令安装。
因为目前没有表单提交接口,还是通过之前的接口进行测试,重新修改的request_handler函数是否正确,示例代码
#!/usr/bin/python
# -*- coding: utf-8 -*-
from common.request_handler import request_handler
method = 'post'
url = 'https://api2.mubu.com/v3/api/user/phone_login'
headers = {'Content-Type': "application/json"}
payload = {
"phone": "13528872802",
"password": "Aa12345678",
"callbackType": 0
}
r = request_handler(method, url, headers, payload)
print(r)
输出还是和之前一样,说明重新改写的,应该没有问题,如果以后碰到问题,再修改也没有关系!