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都是根据需要获取或刷新的。

相关推荐
小大宇12 分钟前
Vue知识点-ElementPlus-03提示框+询问+通知
前端·javascript·vue.js
SL_staff18 分钟前
APS动态重排实践:在多品种小批量场景下实现5分钟插单响应
java·开源·产品
captain3761 小时前
Spring MVC(4)-响应
java·spring boot·后端
步行cgn1 小时前
Axios 请求成功但页面不显示:两个前端错误的分析与修正
前端
时间的情敌2 小时前
WebGIS + OpenLayers + GeoServer + PostGIS #量算 #点聚合
前端·geoserver·openlayers
Lichee202 小时前
招行Java 面试知识点梳理:Spring 事务、锁、线程池、集合
java·面试
YDS8292 小时前
Small Spring IOC篇:作用域和FactoryBean
java·后端·spring
Shaoshing2 小时前
LeetCode100 42.接雨水
java·算法·leetcode
枫子有风2 小时前
卡码网盘项目深挖
java·redis·jwt·es·pgvector
不可能片场2 小时前
Electron 发布 cookie 库先查明文再写解密
前端·electron