无法通过请求库将文件上传到API

时间:2019-12-02 21:07:36

标签: python python-3.x python-requests

我正在尝试使手动过程自动化,除了提供其他表单数据外,该过程还需要命中一个端点并上传文件。我收到一个带有我的Python代码的400 Bad Request

这是一个有效的curl请求:

curl -X POST "https://xxxx/backfill" -H "accept: application/json" -H "Content-Type: multipart/form-data" -F "rsid=some_rsid" -F "file=@300038045-backfill.txt;type=text/plain" -H "Authorization: Basic xxx"

这是Python代码:

def create_backfill(backfill_url: str, rsid: str, file_path: str, auth: Tuple[str, str]):
    headers = {'Content-Type': 'multipart/form-data', 'Accept': 'application/json'}
    form_data = {'rsid': rsid}
    files = {'file': (os.path.basename(file_path), open(file_path, 'rb'), 'text/plain')}
    response = requests.post(backfill_url, data=form_data, files=files, headers=headers, auth=auth)
    response.raise_for_status()
    return response.json()

不确定我做错了什么

编辑: 我通过https://httpbin.org运行了两个请求,并获得了这些结果

卷曲:

{
  "args": {},
  "data": "",
  "files": {
    "file": "data\n"
  },
  "form": {
    "rsid": "some_rsid"
  },
  "headers": {
    "Accept": "application/json",
    "Authorization": "Basic xxx",
    "Content-Length": "448",
    "Content-Type": "multipart/form-data; boundary=------------------------929813e67050b28c",
    "Host": "httpbin.org",
    "User-Agent": "curl/7.54.0"
  },
  "json": null,
  "origin": "192.150.9.200, 192.150.9.200",
  "url": "https://httpbin.org/post"
}

Python:

{
  "args": {}, 
  "data": "", 
  "files": {}, 
  "form": {}, 
  "headers": {
    "Accept": "application/json", 
    "Accept-Encoding": "gzip, deflate", 
    "Authorization": "Basic xxx", 
    "Content-Length": "32", 
    "Content-Type": "multipart/form-data", 
    "Host": "httpbin.org", 
    "User-Agent": "python-requests/2.22.0"
  }, 
  "json": null, 
  "origin": "192.150.9.200, 192.150.9.200", 
  "url": "https://httpbin.org/

0 个答案:

没有答案
相关问题