python

关注公众号 jb51net

关闭
首页 > 脚本专栏 > python > python实现一次获取token,多次使用token

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

作者:changyixue

这篇文章主要介绍了如何用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()

运行结果:

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

您可能感兴趣的文章:
阅读全文