In the requests library, the requests request method, when sending a request with a request body such as post/put/delete, has json and data as optional parameters.
As we all know, there are four main request body formats for http requests:
application/json
applicaiton/x-www-from-urlencoded
multipart/form
application/xml
So what parameters are used for the above request formats?
Next one by one example.
The first type: application/json
Step 1: Find an application/json request interface
If you want to learn automated testing, here I recommend a set of videos for you. This video can be said to be the number one automated testing tutorial on the entire network at station B. At the same time, the number of people online has reached 1,000, and there are notes to collect and share with you. Dashen Technical Exchange: 798478386
The second type: applicaiton/x-www-from-urlencoded
Step 1: Find an application/x-www-from-urlencoded request interface
Step 2: Initiate an http request in x-www-from-urlencoded format - use the data parameter
The specific code is as follows:
The third type: multipart/form
Step 1: Find an upload interface for a multipart/form request
Step 2: Initiate an http request in multipart/form format - using data and files parameters
Complete requests processing upload interface
The fourth type: application/xml
Step 1: Design an interface in xml format
Now use flask to design a simple login interface in xml format, and the request parameters are username and password.
The code is as follows (to run locally, please install the flask library first. Put the following code in app.py):
from flask import Flask, request, Response
app = Flask(__name__)@app.route('/login', methods=['POST'])
def login():
# 获取请求体中的XML数据
xml_data = request.data
# 解析XML数据,提取用户名和密码
try:
import xml.etree.ElementTree as ET
root = ET.fromstring(xml_data)
username = root.find('username').text
password = root.find('password').text
except Exception:
# 解析失败,返回错误响应
response_xml = '0请求格式错误'
return Response(response_xml, mimetype='text/xml')
# 验证用户名和密码
if username == 'python' and password == '1234567890':
# 登录成功,返回成功响应 response_xml = '1成功1001'
else:
# 登录失败,返回失败响应
response_xml = '-1用户名或密码错误'
return Response(response_xml, mimetype='text/xml')if __name__ == '__main__':
app.run()
The requested data xml format is as follows:
<login>
<username>python</username>
<password>1234567890</password>
</login>
The response data xml format is as follows:
<response>
<code>1</code>
<message>成功</message>
<userid>1001</userid>
</response>
In local pycharm, use python app.py to run this service,
Step 2: Initiate an http request in xml format - use the data parameter
data is a string type and is data in xml format.