You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Locust如何仅针对特定状态码重试任务,其余状态码按默认逻辑处理?

解决Locust中仅对401状态码重试、其余状态码按默认逻辑处理的问题

嘿,这个问题我之前也碰到过!当你启用catch_response=True后,Locust就把请求成败的判定权完全交给你了,不再自动根据HTTP状态码(比如503、404这些)标记失败。不过咱们只需要手动调用response.success()和response.failure()方法,就能轻松实现你要的需求:仅对401做重试处理,其他情况完全遵循Locust的默认逻辑(2xx算成功,非2xx算失败)。

修改后的代码示例

import logging
from locust import task, RescheduleTaskImmediately

@task
def list_claims(self):
    with self.client.get(
        "/api/1.0/claim/", 
        name="LIST claims", 
        headers=self.headers, 
        catch_response=True
    ) as response:
        if response.status_code == 401:
            logging.info("401 - Need to fetch a new access token!") # usually happens when the access tokens expires after an hour
            self.aad_b2c_auth()
            raise RescheduleTaskImmediately() # re-run this task with the newly refreshed token
        # 还原Locust默认的成败判定逻辑
        elif response.ok:
            response.success()
        else:
            # 将状态码和响应内容作为失败原因,方便后续排查问题
            response.failure(f"Request failed with status code {response.status_code}: {response.text}")

关键逻辑说明

  1. 401的特殊处理:保留你原来的逻辑,遇到401时刷新令牌并抛出RescheduleTaskImmediately,让任务立刻重试。
  2. 默认逻辑还原:
    • 用response.ok判断状态码是否在200-299之间(这是Locust默认判定成功的范围),如果是就调用response.success()标记请求成功。
    • 其他所有非2xx的状态码(比如503、404等),调用response.failure()并传入错误信息,这样这些请求就会被Locust统计为失败,和默认行为完全一致。

简化写法小技巧

如果你觉得判断分支有点啰嗦,也可以把默认逻辑合并成一行:

if response.status_code == 401:
    # 401处理逻辑
else:
    response.success() if response.ok else response.failure(f"Failed with status {response.status_code}")

这样调整后,你的任务既保留了401自动重试的功能,又能让其他状态码按照Locust的默认规则被正确统计,完美解决你的问题!

内容的提问来源于stack exchange,提问作者silent

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 22:23:13