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

如何将Locust HttpSession的catch_response默认值设置为True?

如何将Locust HttpSession的catch_response默认值设为True

当然有办法啦!下面给你两种实用的方案,你可以根据自己的需求选择:

1. 子类化HttpSession,重写请求方法

这是最直接也最可控的方式,你可以创建一个自定义的Session类,覆盖get、post等请求方法,把catch_response的默认值从False改成True:

from locust import HttpSession

class CustomHttpSession(HttpSession):
    def get(self, path, **kwargs):
        # 给catch_response设置默认值True,其他参数保持原样
        kwargs.setdefault("catch_response", True)
        return super().get(path, **kwargs)
    
    def post(self, path, data=None, json=None, **kwargs):
        kwargs.setdefault("catch_response", True)
        return super().post(path, data=data, json=json, **kwargs)
    
    # 如果你用到put、delete等其他请求方法,同样重写它们即可

然后在你的User类里使用这个自定义的Session:

from locust import User

class MyUser(User):
    def __init__(self, environment):
        super().__init__(environment)
        self.client = CustomHttpSession(
            base_url=self.host,
            environment=self.environment,
            user=self
        )

之后你调用self.client.get()或者self.client.post()时,默认就会带上catch_response=True,不用每次手动指定了。

2. 使用装饰器包装请求方法

如果不想子类化整个Session,也可以写一个轻量的装饰器,给所有请求方法自动加上catch_response=True的默认值:

from functools import wraps
from locust import HttpUser

def default_catch_response(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        kwargs.setdefault("catch_response", True)
        return func(*args, **kwargs)
    return wrapper

class MyHttpUser(HttpUser):
    def __init__(self, environment):
        super().__init__(environment)
        # 给client的请求方法批量加上装饰器
        self.client.get = default_catch_response(self.client.get)
        self.client.post = default_catch_response(self.client.post)
        # 其他需要的请求方法同理处理

这种方式改动更小,适合快速修改现有HttpUser的场景。

小提示

不管用哪种方法,如果你偶尔需要catch_response=False的特殊场景,依然可以手动传入catch_response=False来覆盖默认值,完全不影响灵活使用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 01:32:48