“This is the 29th day of my participation in the Gwen Challenge in November. See details of the event: The Last Gwen Challenge in 2021”
preface
The requests library appears in many of the code examples. Some of you may be wondering what this is and why it’s there. In the end, the Requests library looks like code, but what it does, we can think of it as an interface testing tool.
requests
Attach the Requests document address
Needless to say, it can meet your daily HTTP protocol interface testing and want to use it for anything else.
Code to implement your first interface test
PIP install requests # Install requests library
- For example, the user login interface is /login/ByMobile
import requests
url = "http://127.0.0.1:5000/login/ByMobile"
data = {'zone': 86.'mobile': 13800138000.'code': 1231}
res = requests.get(url,params = data)
print(res)
Copy the code
- First step guide library, you want to use which library function, first introduce it;
- Step 2 Prepare parameters: interface address, parameters, and request mode for requests
-
- Parameters need to be mentioned. In all cases, parameters are displayed as dict data types
- The third step debugging results, directly printed output is the response status code
Test the output of the RES request result object
print(res)
print(res.status_code) # output: 200
print(res.json()) {'code': 0, 'MSG ':' login successful '}
print(res.text) # output:
{
"code": 0."msg": "Login successful"
}
print(res.content) # output binary: b '{\ n "code" : 0, \ n "MSG" : "\ xe7 \ x99 \ XBB \ xe5 \ XBD \ x95 \ xe6 \ x88 \ x90 \ xe5 \ x8a \ x9f" \ n} \ n'
print(res.headers) {' content-type ': 'application/json', 'Content-Length': '42', 'Server': 'Werkzeug/1.0.1 Python/3.7.5', 'Date': 'Tue, 30 Nov 2021 10:04:29 GMT'}
Copy the code
- This is roughly the usual output for the Requests response object; Does it feel very rich.
Follow the gourd
Requests supports get, POST, and other common methods, as well as receiving and requesting requests with different parameters, including forms, JSON objects, params, and upload files.
What matters is that we need encapsulation, which means that internal requests parameters and forms are correct regardless of how they are passed. So here we need to package, will request this tool library in the package
import json
import requests
from utils.logger import getLog
log = getLog()
class HandleRequests(object) :
Classdocs: Requests encapsulates a layer of data/JSON requests.
def __init__(self) :
Constructor: Initialize the Requests object.
self.http = requests.Session()
def __call__(self, method, url, data=None, **kwargs) :
""" magic method call """
self.method = method.upper()
if isinstance(data, str) :try:
data = json.loads(data)
except json.JSONDecodeError as error:
data = eval(data) log.error("{} data contains Python objects such as None\False\True, which can no longer be turned into dict objects :{}".format(data, error))
if self.method == "POST":
res = self.http.request(self.method, url, json=data, verify=True, **kwargs)
elif self.method == "GET":
res = self.http.request(self.method, url, params=data, verify=True, **kwargs)
else:
log.info("Request method {}, not supported yet!!".format(self.method))
return res
Copy the code
extension
Speaking of the Requests library, haven’t you tested the WebService interface with it?
Sorry, it really doesn’t seem to have one. Instead, use the SUDS third-party library to do it.
- Using python2.7 as an example, download suds
Doctor import ImportDoctor, import from suds.client import client Just information client information when it is output less imp = Import (' http://www.w3.org/2001/XMLSchema ', Location = 'http://www.w3.org/2001/XMLSchema.xsd') imp. Filter. The add (' http://WebXml.com.cn/ ') doctor = ImportDoctor # (imp) address url="http://www.webxml.com.cn/webservices/qqOnlineWebService.asmx?wsdl" client=Client(url,doctor=doctor) # Print all information about the WebService interface: Including the request method, the parameters such as print client res = client. The service. The qqCheckOnline (" 1251111111 ") # output the deployment of the XML format, but is the label to the value of the print resCopy the code