request登录

获取token登录

import requests
import json
import yaml

def get_token():
    '''
    请求登录接口,获取token
    :return:
    '''
    headers = {"Content-Type": "application/json;charset=utf8"}
    url = "http://127.0.0.1:5000/login"
    _data = {
        "username": "刘德华",
        "password": "123456"
    }
    res = requests.post(url=url, headers=headers, json=_data).text
    res = json.loads(res)
    token = res["token"]
    return token


def write_yaml(token):
    '''
    写入yaml文件
    :return:
    '''
    t_data = {
        "token": token
    }
    with open("yaml文件路径", "w", encoding="utf-8") as f:
        yaml.dump(data=t_data,  stream=f, allow_unicode=True)


if __name__ == '__main__':
    token = get_token() # 获取token
    write_yaml(token)   # 将token值写入yaml文件

持久化存储

import requests
import yaml
import pytest
import json

def read_yaml():
    '''
    读yaml文件
    :return:
    '''
    with open('yaml文件路径', 'r', encoding='utf-8') as f:
        result = yaml.load(f.read(), Loader=yaml.FullLoader)
    token = result["token"]
    return token


def test_check_user():
    '''
    查询个人信息(需要先登录系统)
    :return:
    '''
    # 先从yaml文件中读取token
    token = read_yaml()
    # 再将token添加到请求头中
    headers = {
        "Content-Type": "application/json;charset=utf8",
        "token": token
    }

    url = "http://127.0.0.1:5000/users/3"
    res = requests.get(url=url, headers=headers).text
    # 返回结果为json格式,转换为字典
    res = json.loads(res)
    # 断言code是否为1000
    assert res["code"] == 1000


if __name__ == '__main__':
    pytest.main()

文章搬运
https://www.cnblogs.com/lfr0123/p/16105842.html

posted @   17。  阅读(64)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· DeepSeek “源神”启动!「GitHub 热点速览」
· 我与微信审核的“相爱相杀”看个人小程序副业
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· C# 集成 DeepSeek 模型实现 AI 私有化(本地部署与 API 调用教程)
· spring官宣接入deepseek,真的太香了~
点击右上角即可分享
微信分享提示