Detailed post request for automated testing of Python interface

Table of contents

foreword

requests.post() parameter description

Send a post request (the request parameter format is dict)

Send a post request (the request parameter format is json)

Summarize

Written at the end, a little suggestion


foreword

In the HTTP protocol, unlike the get request, which puts the request parameters directly in the url, the request data of the post request needs to be passed in the message body (request body).

Moreover, the protocol does not stipulate what kind of encoding method must be used for the request data of the post request, so the request data can have different encoding methods. The server knows what the message body in the request is through the Content-Type field in the request header. One encoding method, and then parse the message body in a corresponding way.

The commonly used encoding methods for post request parameters are as follows:

application/x-www-form-urlencoded		                # form表单格式,非常常见
multipart/form-data						# 一般用于上传文件,较为常见
application/json						# json字符串格式,非常常见
text/xml							# xml格式

Regarding post request parameters, there will be an article dedicated to it later, so I won’t elaborate too much here.

requests.post() parameter description

Use the post method provided by the requests library to send a post request. The source code of requests.post() is as follows:

def post(url, data=None, json=None, **kwargs):
    r"""Sends a POST request.

    :param url: URL for the new :class:`Request` object.
    :param data: (optional) Dictionary, list of tuples, bytes, or file-like
        object to send in the body of the :class:`Request`.
    :param json: (optional) json data to send in the body of the :class:`Request`.
    :param \*\*kwargs: Optional arguments that ``request`` takes.
    :return: :class:`Response <Response>` object
    :rtype: requests.Response
    """

    return request('post', url, data=data, json=json, **kwargs)

Parameter Description:

  1. url, request URL

  2. data, dictionary, tuple list, byte or file object to be sent to the specified URL, optional (can be filled or left blank)

  3. json, the JSON object to send to the specified URL, optional

  4. **kwargs, you can add other request parameters, such as headers, timeout, cookies, etc.

The encoding format commonly used in the post interface corresponds to the format of the request parameter in the python script. Generally, it is dict (dictionary) or json . For example, the format of application/x-www-form-urlencoded corresponds to dict in python, and application/json in python Corresponds to json.

Therefore, an example will be given for each of these encoding formats in the following.

Send a post request (the request parameter format is dict)

Let's take requesting the login interface of the TesterHome network as an example, and send a request whose request parameter format is dict.

The content-type in the request header is application/x-www-form-urlencoded;charset=UTF-8as shown in the figure below:

Then the request parameter encoding format should be dict, the code is as follows:

import requests

def testerhome_login():
    # data为请求入参
    data = {
        "user[login]": "账号",
        "user[password]": "密码",
        "user[remember_me]": 0,
        "commit": "登录"
    }
    headers = {
        "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/53\
        7.36 (KHTML, like Gecko) Chrome/98.0.4758.82 Safari/537.36"
    }
    url = "https://testerhome.com/account/sign_in"
    
    # 编码格式为application/x-www-form-urlencoded;charset=UTF-8,所以请求参数为dict,使用data参数
    res = requests.post(url=url, headers=headers, data=data)
    print(res.text)
    print(res.status_code)


if __name__ == '__main__':
    testerhome_login()

The result of the operation is as follows:

From the printed returned content, we can judge that the interface request is successful.

Send a post request (the request parameter format is json)

Here I use the flask framework to write a simple simulation interface to demonstrate, the interface code is as follows:

from flask import Flask, jsonify, request

app = Flask(__name__)
app.config["JSON_AS_ASCII"] = False

@app.route("/login", methods=["POST"])
def login():
    username = request.json.get("username").strip()
    password = request.json.get("password").strip()
    print(username, password)
    if username and password:
        if username == "lilei" and password == "123456":
            return jsonify(
                {"code": 1000, "msg": "登录成功!", "token": "sh34ljjl08s32730dj"}
            )
        elif username == "hanmeimei" and password == "888888":
            return jsonify(
                {"code": 1000, "msg": "登录成功!", "token": "hjf078977l08ert2323k"}
            )
        else:
            return jsonify(
                {"code": 1001, "msg": "账号或密码错误!"}
            )
    else:
        return jsonify(
            {"code": 1002, "msg": "账号或密码不能为空!"}
        )

if __name__ == '__main__':
    app.run()

Note that you need to install the flask framework first, and then run the module. For details, please refer to my previous article on using Flask to develop a simple interface . After running, we can see the host address of the interface service, as follows:

The request parameter format of this interface needs to be json, and requests.post() requests this interface code as follows:

import requests
import json

headers = {"Content-Type": "application/json;charset=utf8"}
url = "http://127.0.0.1:5000/login"
_data = {
    "username": "lilei",
    "password": "123456"
}

# 这里使用json参数,即json=_data
res = requests.post(url=url, headers=headers, json=_data).text
# 当然还可以使用data参数,但需先将_data转换为json格式,即data=json.dumps(_data)
# json.dumps()将dict格式转换成json格式
res = requests.post(url=url, headers=headers, data=json.dumps(_data)).text
print(res)

The result of the operation is as follows:

Summarize

For post requests, due to the encoding format of the request body, when using requests.post(), you need to select the specified encoding format for the request parameters according to the Content-Type field in the interface request header before sending the request. In fact, the request parameters of the get request also have their corresponding encoding formats. As for how to determine the format of the get and post request parameters, let’s listen to the detailed explanation in the next chapter.

Written at the end, a little suggestion

Finally, when you want to step into this industry, here are two small suggestions:

(1) You need to think about it yourself, do you really like this industry, at least have enough enthusiasm to delve into it? Because the technology of the IT industry is developing very fast, continuous learning can ensure a long-term progress in this industry. If you don't like learning new technologies, even if you enter this industry, you will be eliminated soon.

(2) The high salary in the Internet industry will not be given to you for no reason . Overtime is inevitable. You need to figure out whether you can accept this kind of work intensity.

If the answer you give is yes, then you don’t have to hesitate anymore, just go on firmly, in this industry and in this position, you will definitely get a corresponding return for your efforts.

If the following materials are available, they can be taken directly:

1. Complete project source code and environment necessary for self-study development or testing

2. All templates in the test work (test plan, test case, test report, etc.)

3. Classic software testing interview questions

4. Python/Java automated testing practice.pdf

5. Jmeter/postman interface test full set of video acquisition

6. Python learning roadmap

Focus : Supporting learning materials and video teaching

So here I have also carefully prepared the detailed information of the above outline, including: e-books, resume templates, various job templates, interview guides, self-study projects, etc. Please contact me if necessary, and look forward to interacting with you.

Guess you like

Origin blog.csdn.net/weixin_67553250/article/details/127651669