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

Locust中使用FastHttp时如何对报告内不同参数的失败API分组

问题原因

FastHttpUser 底层依赖 geventhttpclient 库,其失败请求的默认上报逻辑没有读取请求时传入的name参数作为分组标识,而是直接使用完整请求URL(含动态查询参数)生成失败条目,这才导致不同手机号的失败请求被拆分到不同列,只有Statistics统计部分会读取name参数做聚合。

修复方案

你可以通过自定义请求事件回调的方式,强制失败请求按name参数分组,操作步骤如下:

  • 第一步:全局注册请求失败钩子,覆盖默认的分组逻辑
from locust import FastHttpUser, task, events

# 全局监听请求事件,异常场景下强制用name参数作为分组标识
@events.request.add_listener
def handle_request_failure(request_type, name, response_time, response_length, exception, **kwargs):
    if exception:
        kwargs["request_name"] = name

class YourTestUser(FastHttpUser):
    @task
    def check_user(self):
        # 你的随机手机号生成逻辑
        self.phone_no = "生成的随机手机号"
        # 原有请求逻辑保留name参数即可
        self.client.get(
            f"/api/v1/users/checkuser?phone_number={self.phone_no}", 
            name="/api/v1/users/checkuser"
        )
  • 第二步:如果全局钩子不生效,可以改为手动捕获异常上报
@task
def check_user(self):
    self.phone_no = "生成的随机手机号"
    group_name = "/api/v1/users/checkuser"
    try:
        with self.client.get(
            f"/api/v1/users/checkuser?phone_number={self.phone_no}",
            name=group_name,
            catch_response=True
        ) as response:
            if response.status_code >= 400:
                response.failure(f"状态码异常:{response.status_code}")
    except Exception as e:
        # 手动上报异常,指定分组名
        self.environment.events.request.fire(
            request_type="GET",
            name=group_name,
            response_time=0, # 可自行统计实际请求耗时填入
            response_length=0,
            exception=e,
            context={}
        )

修改后重新运行压测,所有失败请求都会统一聚合到/api/v1/users/checkuser分组下,不会再按手机号拆分多列。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 02:24:02