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

運行結果:

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