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

Locust脚本中如何将Post请求硬编码ID替换为列表参数

解决Locust脚本中Post请求动态传入列表参数的问题

你需要把硬编码的ID列表替换为动态的all_pp_ids列表,推荐两种简洁可靠的实现方式:

方法一:使用json.dumps序列化请求体

先导入json模块,构造包含all_pp_ids的字典,再序列化为JSON字符串传给data参数:

import json

# ... 其他代码 ...

@task(2)
def generate_bids_for_all_powerplants(self):
    # 构造包含目标列表的请求体字典
    request_body = {"powerPlantIds": all_pp_ids}
    response = self.client.post(
        f'https://example.com/bids/generate',
        headers={"Authorization": f'Bearer {token}', "Content-Type": 'application/json'},
        data=json.dumps(request_body),
        name='/bids/generate'
    )
    print("Response: ", response.request.body)
    print("All ids: ", all_pp_ids)

方法二:直接使用json参数(推荐)

Locust的client.post支持直接传入json参数,会自动完成JSON序列化并设置正确的Content-Type请求头,代码更简洁:

# ... 其他代码 ...

@task(2)
def generate_bids_for_all_powerplants(self):
    response = self.client.post(
        f'https://example.com/bids/generate',
        headers={"Authorization": f'Bearer {token}'},
        json={"powerPlantIds": all_pp_ids},
        name='/bids/generate'
    )
    print("Response: ", response.request.body)
    print("All ids: ", all_pp_ids)

注意事项

  • 确保all_pp_ids在当前函数的作用域内可访问,如果是类实例属性,记得写成self.all_pp_ids
  • 第二种方法无需手动指定Content-Type,Locust会自动添加application/json头

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 07:29:57