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
相关产品推荐
相关产品推荐

