用python脚本实现一次获取token,多次使用token

1.编写配置文件Token.yaml(暂时为空),用来存放token值

另外:用命令:pip3 install ruamel.yaml安装ruamel.yaml模块,用以去除yaml文件中的大括号

用python脚本实现一次获取token,多次使用token_第1张图片

2.编写鉴权文件testingedu_auth.py,用于获取token值并存储token值:

#!/usr/bin/env python 
# -*- coding:utf-8 -*-
# 用pip3命令安装
import requests
from ruamel import yaml


def test_testingedu_auth():
    url = "http://www.XXX.com.cn/XXX/HTTP//auth"
    headers = {"Content-Type": "application/json"}

    # 发送请求
    response = requests.post(url=url, headers=headers)

    print(response.text)
    print(response.status_code)
    print(response.json()["token"])
    # return response.json()["token"]

    # 把token值写入配置文件中
    # cur = os.path.dirname(os.path.realpath(__file__))
    # p = os.path.join(cur, 'Token.yaml')
    yamlpath = r'C:\Users\Administrator\PycharmProjects\APITest\common\Token.yaml'
    tokenValue = {
        'token': response.json()["token"],
    }
    with open(yamlpath, "w", encoding="utf-8") as f:
        yaml.dump(tokenValue, f, Dumper=yaml.RoundTripDumper)


if __name__ == "__main__":
    test_testingedu_auth()

运行结果:

查看Token.yaml中的值:

3.编写获取token值的脚本:get_token.py,方便其他接口调用(登录、查看和退出)

#!/usr/bin/env python 
# -*- coding:utf-8 -*-
import yaml
import os


# cur = os.path.dirname(os.path.realpath(__file__))

def get_token(yamlName = "Token.yaml"):

    # 从配置文件中读取token值,并返回
    p = os.path.join(r'C:\Users\Administrator\PycharmProjects\APITest\common\Token.yaml')
    f = open(p)
    a = f.read()
    t = yaml.load(a)
    f.close()
    return t["token"]

if __name__ == "__main__":
    get_token()

4.编写登录接口脚本:testingedu_login.py

#!/usr/bin/env python 
# -*- coding:utf-8 -*-
import requests
from common.get_token import get_token


def testingedu_login():
    url = "http://www.XXX.com.cn/XXX/HTTP//login?username=XXX&password=XXX"
    headers = {"token": get_token()}
    response = requests.post(url=url, headers=headers)
    print("返回体是:", response.text)
    print("状态码是:", response.status_code)


if __name__ == "__main__":
    testingedu_login()

运行结果:

用python脚本实现一次获取token,多次使用token_第2张图片

5.编写查看接口脚本:testingedu_info.py

#!/usr/bin/env python 
# -*- coding:utf-8 -*
import requests
from common.get_token import get_token


def testingedu_info():
    url = "http://www.XXX.com.cn/XXX/HTTP//getUserInfo?id=XXX"
    headers = {"token": get_token()}

    response = requests.post(url=url, headers=headers)
    print(response.text)
    print(response.status_code)


if __name__ == "__main__":
    testingedu_info()

运行结果:

6.编写退出接口脚本:testingedu_logout.py

#!/usr/bin/env python 
# -*- coding:utf-8 -*-
import requests
from common.get_token import get_token


def testingedu_logout():
    url = "http://www.XXX.com.cn/XXX/HTTP//logout"
    headers = {"token": get_token()}
    response = requests.post(url=url, headers=headers)
    print(response.text)
    print(response.status_code)


if __name__ == "__main__":
    testingedu_logout()

运行结果:

用python脚本实现一次获取token,多次使用token_第3张图片

你可能感兴趣的:(接口测试)