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

cURL调用API上传文件成功,Python requests调用失败求助

Polarion API 文件上传:cURL正常但Python requests报错400解决方法

问题场景

使用cURL命令上传文件到Polarion的Work Item附件API可正常运行,但对应的Python requests代码调用返回400 Bad Request错误。

可用的cURL命令

curl -X POST "http://<DOMAIN>/polarion/rest/v1/projects/<PROJECT_ID>/workitems/<WORKITEM_ID>/attachments" \
  -H "Authorization: Bearer <TOKEN>" \
  -H "accept: application/json" \
  -H "Content-Type: multipart/form-data" \
  -F resource="{\"data\": [{\"type\": \"workitem_attachments\",\"attributes\": {\"fileName\": \"test.txt\",\"title\": \"test\"}}]}" \
  -F files=@"test.txt"

出错的Python代码

import requests
import json

url = "http://<DOMAIN>/polarion/rest/v1/projects/<PROJECT_ID>/workitems/<WORKITEM_ID>/attachments"

headers = {
    "Content-Type": "multipart/form-data",
    "accept": 'application/json',
    "Authorization": "Bearer " + token
}

data = {
    "data": [
        {
            "type": "workitem_attachments", 
            "attributes": {
                "fileName": "test.txt",
                "title": "test"
            }
        }
    ]
}

files = {
    'resource': (None, json.dumps(data)),
    'files': ("test.txt", open('test.txt', 'rb'))
}

r = requests.post(url, files=files, headers=headers)

返回错误

{"errors":[{"status":"400","title":"Bad Request","detail":null,"source":null}]}

问题原因与修复方案

核心问题

  1. 手动设置Content-Type: multipart/form-data:requests库在处理files参数时,会自动生成包含boundary分隔符的正确Content-Type头。手动设置该头会覆盖自动生成的值,导致API无法正确解析多部分请求体。
  2. 未指定resource字段的Content-Type:cURL中提交的resource参数是JSON格式,需要明确告知API该字段的类型为application/json,否则API可能无法识别JSON结构。

修正后的Python代码

import requests
import json

url = "http://<DOMAIN>/polarion/rest/v1/projects/<PROJECT_ID>/workitems/<WORKITEM_ID>/attachments"

# 移除手动设置的Content-Type,保留必要的授权和接受类型头
headers = {
    "accept": 'application/json',
    "Authorization": "Bearer " + token
}

data = {
    "data": [
        {
            "type": "workitem_attachments", 
            "attributes": {
                "fileName": "test.txt",
                "title": "test"
            }
        }
    ]
}

# 为resource字段添加application/json的Content-Type指定
files = {
    'resource': (None, json.dumps(data), 'application/json'),
    'files': ("test.txt", open('test.txt', 'rb'))
}

r = requests.post(url, files=files, headers=headers)
# 可选:打印响应结果排查
print(r.status_code)
print(r.text)

说明

  • 移除headers中的Content-Type后,requests会自动生成类似multipart/form-data; boundary=xxxx的正确头,确保API能识别请求体的分隔方式。
  • 为resource字段添加第三个参数'application/json',与cURL提交JSON参数的行为对齐,让API正确解析该字段的内容。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 12:30:07