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

1.两种格式的文件:

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

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

2)编写配置文件access_token.yml,把token值写到配置文件中的关键代码如下:

# 把token值写到配置文件access_token.yml中
def write_token(res):
    curPath = os.path.abspath(os.path.dirname(__file__))
    yamlPath = os.path.abspath(os.path.dirname(curPath) + os.path.sep + "configs/access_token.yml")
    # yamlPath = os.path.dirname(os.path.abspath('.'))+'/data/access_token.yml'
    # res = json.loads(res)

    tokenValue = {
        'access_token': res["access_token"]
    }
    with open(yamlPath, 'w', encoding='utf-8') as f:
        yaml.dump(tokenValue, f)

    logger.info("\n token值已保存至配置文件中")

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()

运行结果:

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()

运行结果:

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章