pytest中token的一种处理方法

在某个场景中,各个接口经常需要使用到token,而且接口对频繁登录做了防抖,无法频繁调用。考虑了很多方法,发现总是有一些或多或少的弊端,这里在conftest中定义了一个钩子函数用于处理token。

复制代码
@pytest.fixture(scope="module")
def auth_tokens(refresh_threshold=600):  # 假设刷新阈值为10分钟
    tokens = {}
    def get_or_refresh_token(username):
        token_info = tokens.get(username)
        if not token_info or (time.time() - token_info['timestamp']) > refresh_threshold:
            logger.info(f"没有获取到该账号{username}的token,或者token已过期,重新获取token中")
            token = login_user(username, '222222').response.json()['data']['accessToken']
            tokens[username] = {'token': token, 'timestamp': time.time()}
        logger.info(f"{username}的token为{tokens[username]['token']}")
        return tokens[username]['token']
    return get_or_refresh_token

作用域定义为模块级,在整个模块中只执行一次。

定义了一个get_or_refresh_token闭包,该闭包负责根据用户名获取或刷新token。虽然auth_tokens fixture在模块级别只实例化一次,但是它返回的闭包(get_or_refresh_token)能够对每个传入的用户名进行独立的操作,确保每个账号的token都是根据需要获取或刷新的。

相关推荐
萧行之22 分钟前
Ubuntu Node.js 版本管理工具 n 完整安装与使用教程
linux·前端
星晨雪海23 分钟前
企业标准 DTO 传参 + Controller + Service + 拷贝工具类完整版
java·开发语言·python
devlei7 小时前
从源码泄露看AI Agent未来:深度对比Claude Code原生实现与OpenClaw开源方案
android·前端·后端
pshdhx_albert7 小时前
AI agent实现打字机效果
java·http·ai编程
Jagger_8 小时前
周末和AI肝了两天,终于知道:为什么要把AI当做实习生
前端
weixin_456164838 小时前
vue3 子组件向父组件传参
前端·vue.js
沉鱼.448 小时前
第十二届题目
java·前端·算法
Setsuna_F_Seiei8 小时前
CocosCreator 游戏开发 - 多维度状态机架构设计与实现
前端·cocos creator·游戏开发
Bigger9 小时前
CodeWalkers:让 AI 助手化身桌面宠物,陪你敲代码的赛博伙伴!
前端·app·ai编程
赫瑞9 小时前
数据结构中的排列组合 —— Java实现
java·开发语言·数据结构