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

如何用Python将InMemoryUploadedFile通过requests发送请求并获取200状态?

问题描述

我在Postman中按如下方式发送数据:
Postman发送数据示例

我的Python代码如下:

headers = {
        "Accept": "*/*",
        "Content-Type": "multipart/form-data; boundary=974767299852498929531610575",
    }

response = requests.request(
            "POST",
            LINK,
            headers=headers,
            data={
                'product_id': 1,
                'product_images': [file, ]
              }
)

其中file为InMemoryUploadedFile格式,但请求报错。我还尝试了:

file = my_file.file.getvalue()

但仍然报错。请问如何修改代码以获取200状态码?有什么解决思路吗?

解决方法及思路
  • 不要手动设置Content-Type头
    requests库会自动处理multipart/form-data请求的边界值和Content-Type头,手动指定边界值会导致请求格式不匹配,直接删除自定义的Content-Type配置。

  • 使用files参数上传文件
    发送文件时不能把文件放在data参数里,要改用files参数。针对你的场景,代码可修改为:

    headers = {
        "Accept": "*/*"
    }
    
    # 构造files参数,非文件字段用None作为文件名占位
    files = {
        'product_id': (None, '1'),
        'product_images': (my_file.name, my_file, my_file.content_type)
    }
    
    response = requests.post(LINK, headers=headers, files=files)
    

    若需上传多个文件,product_images可写成列表形式:

    files = {
        'product_id': (None, '1'),
        'product_images': [
            (file1.name, file1, file1.content_type),
            (file2.name, file2, file2.content_type)
        ]
    }
    
  • 正确处理InMemoryUploadedFile
    无需调用getvalue()转成字节流,直接将InMemoryUploadedFile对象传入files参数即可,requests会自动处理文件读取逻辑。

  • 调试建议

    • 打印response.text或response.json()查看后端返回的具体错误信息,明确问题根源
    • 对比Postman的Raw请求内容与requests发送的请求,通过print(response.request.headers)和print(response.request.body)检查格式差异

内容的提问来源于stack exchange,提问作者Anna Berezko

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 05:12:04