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

相关推荐
Remember_9933 分钟前
【数据结构】深入理解排序算法:从基础原理到高级应用
java·开发语言·数据结构·算法·spring·leetcode·排序算法
wanzhong23334 分钟前
开发日记13-响应式变量
开发语言·前端·javascript·vue
indexsunny4 分钟前
互联网大厂Java求职面试实战:Spring Boot微服务与Kafka消息队列场景解析
java·spring boot·面试·kafka·microservices·interview·distributed systems
qq_12498707534 分钟前
基于Spring Boot的心理咨询预约微信小程序(源码+论文+部署+安装)
java·spring boot·后端·spring·微信小程序·小程序·毕业设计
jiayong235 分钟前
Tomcat Servlet容器与生命周期管理面试题
java·servlet·tomcat
代码游侠7 分钟前
学习笔记——文件传输工具配置与Makefile详解
运维·前端·arm开发·笔记·学习
彭于晏Yan9 分钟前
SpringBoot集成Druid连接多个数据源
java·spring boot·后端
拽着尾巴的鱼儿10 分钟前
fixedBug:Web Requeset Get请求URLEncoder 编码
java
踢球的打工仔12 分钟前
typescript-类的静态属性和静态方法
前端·javascript·typescript
lkbhua莱克瓦2412 分钟前
Apache Maven全面解析
java·数据库·笔记·maven·apache