Apply the requests library in python to simulate the postman request to carry the token, and use the get and post methods to request the header to carry the token

background:

In actual development, the Python program needs to call the background interface to act as the front end, and the back end stipulates that the request header needs to carry token

Encapsulated get and post classes:

class RequestMethodCarryJson:
    """
    定义请求类型
    以json方式传递参数
    """

    def __init__(self):

        """初始化参数"""
        self.data = {}
        self.files = {}

    def get(self, url, data, headers):
        """
        定义get方法请求
        :return:
        """
        try:
            return requests.get(url=url, data=data, headers=headers, timeout=60)
        except TimeoutError:
            return print('%s get request timeout!' % url)

    def getCarryToken(self, url, data, headers):
        """
        定义get方法请求
        :return:
        """
        try:
            return requests.get(url=url, json=data, headers=headers, timeout=60)
        except TimeoutError:
            return print('%s get request timeout!' % url)

    def post(self, url, data, headers):
        """
        定义post方法请求
        post携带token,看起来不需要像get那样添加一个getCarryToken特有的识别方法
        :return:
        """
        try:
            return requests.post(url=url, data=json.dumps(data), headers=headers, timeout=60)
        except TimeoutError:
            return print('%s post request timeout!' % url)
class RequestMethodCarryFormData:
    """
    定义请求类型
    以表单方式form-data传递参数
    """

    def __init__(self):

        """初始化参数"""
        self.data = {}
        self.files = {}

    def get(self, url, data, headers):
        """
        定义get方法请求
        :return:
        """
        try:
            return requests.get(url=url, data=data, headers=headers, timeout=60)
        except TimeoutError:
            return print('%s get request timeout!' % url)

    def getCarryToken(self, url, data, headers):
        """
        定义get方法请求,额外添加token
        :return:
        """
        try:
            return requests.get(url=url, json=data, headers=headers, timeout=60)
        except TimeoutError:
            return print('%s get request timeout!' % url)

    def post(self, url, data, headers):
        """
        定义post方法请求
        这个携带json应该不需要额外改
        :return:
        """
        try:
            return requests.post(url=url, data=data, headers=headers, timeout=60)
        except TimeoutError:
            return print('%s post request timeout!' % url)

Application scenario:

Scenario 1——Headers carry token when get request [pass parameters in json format]:

​token="里面填token内容"
test1Info = test1(token)

def test1(token):
    """
    携带token,
    访问平台已经存在的数据库,
    以json格式传递数据
    :param token:
    :return:
    """
    url = "http://127.0.0.1:8088/backup/url1"
    headers = {'Content-Type': 'application/json;charset=utf-8', 'token': token}
    data = dict()
    data["param1"] = "param1"
    data["param2"] = "param2"
    resp = RequestMethodCarryJson().getCarryToken(url, data, headers).json()
    dbInfo = resp["items"]
    return dbInfo

Scenario 2——Headers carry token during post request [pass parameters in application/x-www-form-urlencoded (form) format]:

token="里面填token内容"
test2Info = test2(token)

def test2(token):
    url = "http://127.0.0.1:8088/testFormData/json/transfer"
    headers = {'Content-Type': 'application/x-www-form-urlencoded', 'token': token}
    data = dict()
    data["param1"] = "param1"
    """
    这里不接受状态码
    """
    resp = RequestMethodCarryFormData().post(url, data, headers).json()
    info = resp["items"]
    if info == "格式正确":
        return True
    else:
        return False

Scenario 3 - Summarize the successful code after stepping on the pit:

    """
    请求头携带token拿取信息:
    1-post-以json格式传递数据,请求头携带token成功
    形如:
    # resp = requests.post(url,json=data,headers=headers).json()
    resp = RequestMethodCarryJson().post(url, data, headers).json()


    2-get-以json格式传递数据,请求头携带token成功
    # resp = requests.get(url,json=data,headers=headers).json()
    resp = RequestMethodCarryJson().getCarryToken(url, data, headers).json()

    :param platformInfo:
    :return:
    """

Extended understanding:

Related information reference:

The difference between form-data and x-www-form-urlencoded in postman - Programmer Sought

python requests with request header Token to initiate http request_python request token_Software Testing Li's Blog

When python sends requests, use the login token value as the request header information of the next interface

Guess you like

Origin blog.csdn.net/Elephantpretty/article/details/131697868