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

Locust框架中使用Requests上传文件返回400错误如何排查

问题排查与修复方案

错误1:手动指定了multipart/form-data请求头

Locust 底层基于 requests 库实现请求发送,当传入files参数时,requests 会自动生成携带boundary分隔符的Content-Type请求头。手动指定该头会丢失边界信息,导致 FastAPI 无法正常解析多表单数据,直接返回400错误。
解决方案:删除手动设置的Content-Type请求头。

错误2:请求端点路径缺失尾部斜杠

curl命令请求的端点为/my_endpoint/(带尾部斜杠),但Locust代码中填写的路径是/my_endpoint(无尾部斜杠)。FastAPI默认开启路径严格匹配,POST请求遇到路径不匹配时不会像GET请求一样自动重定向,会直接返回400错误。
解决方案:将请求路径修改为/my_endpoint/,和curl请求保持一致。

额外优化点:文件句柄未释放

当前代码中每次请求都会调用open()打开文件,但没有显式关闭,长时间压测会导致句柄泄漏。
解决方案:提前读取文件内容复用,或使用上下文管理器管理文件打开操作。

修正后的完整代码

from locust import HttpUser, task

class QuickstartUser(HttpUser):
    # 提前读取文件内容复用,避免每次请求重复打开文件
    with open('./path/to/myfile.jpeg', 'rb') as f:
        test_file_content = f.read()

    @task(1)
    def testClassifier(self):
        headers = {
            'accept': 'application/json',
        }
        files = {
            # 第三个参数指定文件MIME类型,避免服务端识别异常
            'input_file': ('myfile.jpeg', self.test_file_content, 'image/jpeg'),
        }
        response = self.client.post("/my_endpoint/", files=files, headers=headers)
        response.raise_for_status()
        print(response.text)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 00:45:01