【问题标题】:Why does file upload in Python Request throw 400 Error为什么Python请求中的文件上传会抛出400错误
【发布时间】:2021-12-25 20:31:03
【问题描述】:

我正在使用 locust 框架来测试我的一个端点(它需要一个图像文件并尝试对其施展魔法)。服务器正在使用 FastAPI + gunicorn 运行

这是我的 Curl 命令,它给出了正确的响应。

curl -X POST http://localhost:5002/my_endpoint/ -H "accept:application/json" -H "Content-Type: multipart/form-data" -F "input_file=@./path/to/myfile.jpeg"

这是我的蝗虫文件中对应的python代码

class QuickstartUser(HttpUser):
    @task(1)
    def testClassifier(self):
        headers = {
                    'accept': 'application/json',
                    'Content-Type': 'multipart/form-data',
                  }

        files = {
                    'input_file': ('./path/to/myfile.jpeg', open('./path/to/myfile.jpeg', 'rb')),
                }
        response = self.client.request('post',"/my_endpoint", files=files, headers=headers)
        response.raise_for_status()
        print(response)

这是我如何调用蝗虫文件

locust -f deploy/load_testing/locustfile.py --headless --host http://localhost:5002 -u 1 -r 2 --run-time 10s --stop-timeout 9 -L DEBUG --logfile ./locust.log

任何人都可以在这里帮助我我在这里做错了什么吗?

  24   │     raise HTTPError(http_error_msg, response=self)
  25   │ requests.exceptions.HTTPError: 400 Client Error: Bad Request for url: http://localhost:5002/my_endpoint/
  26   │

【问题讨论】:

    标签: python python-requests fastapi locust


    【解决方案1】:

    根据docs files 应该是'filename': file-like-objects 的字典,但您传递的是一个元组而不是值。更改 files 以匹配预期格式

    files = {
        'input_file': open('./path/to/myfile.jpeg', 'rb'),
    }
    response = self.client.request('post',"/my_endpoint", files=files, headers=headers)
    

    【讨论】:

    • 不。仍然失败并出现同样的错误。
    • @AshwinKumar 你是怎么做到的,给我们看一些代码。
    • 第一篇有代码。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-10-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-20
    • 1970-01-01
    相关资源
    最近更新 更多