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}]}
问题原因与修复方案
核心问题
- 手动设置
Content-Type: multipart/form-data:requests库在处理files参数时,会自动生成包含boundary分隔符的正确Content-Type头。手动设置该头会覆盖自动生成的值,导致API无法正确解析多部分请求体。 - 未指定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
相关产品推荐
相关产品推荐

