【问题标题】:cURL multipart/form-data with files to Python requestcURL multipart/form-data 与文件到 Python 请求
【发布时间】:2020-03-20 23:33:35
【问题描述】:

我正在努力将有效的 cURL 命令转换为等效的 Python 请求。 cURL命令如下:

curl -X POST \
  http://localhost:3001/api/v1/document \
  -H 'Content-Type: multipart/form-data' \
  -F 'file=@/home/user1/test.pdf;type=application/pdf' \
  -F 'config=@config.json;type=application/json'

我正在使用 Python 3.6 和 request 库,并且一直在考虑各种方法。其中一个,恕我直言应该可以工作,但在服务器上给出 Error: Multipart: Boundary not found 错误如下:

url = 'http://localhost:3001/api/v1/document'
headers  = {'Content-Type': 'multipart/form-data'}
file = "/home/user1/test.pdf"

files = {
     'file': (file, open(file, 'rb'),'type=application/pdf'),
      'config': ('config.json',open('config.json','rb'),'type=application/json')
 } 

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

我查看了各种在线“翻译”,包括https://curl.trillworks.com/,但没有一个给出有效的答案。还尝试了一些我在其他帖子中发现的变体,例如删除标题中的content-type,或使用json.dump() 而不是open() 函数,但仍然没有成功。

任何帮助将不胜感激!

【问题讨论】:

  • 当您使用files 并添加边界时,尝试删除已设置的标题“multipart/form-data”
  • 我认为type= 也是不必要的
  • 当我删除标题时,我收到 415, Unsupported Media 错误。另外,如何设置边界?
  • type=application/pdf 应该是 application/pdf 而 type=application/json 只是 application/json
  • 谢谢伯特兰。这解决了问题。我需要两者都做,删除标题以及从 pdf 和 json 文件中删除“type =”以使其正常工作。

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


【解决方案1】:

Bertrand Martel 的解决方案最终成功了:

  1. 删除headers
  2. 从 pdf 和 json 文件中删除 'type='

工作解决方案如下所示:

url = 'http://localhost:3001/api/v1/document'

file = "/home/user1/test.pdf"

files = {
     'file': (file, open(file, 'rb'),'application/pdf'),
      'config': ('config.json',open('config.json','rb'),'application/json')
 } 

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-15
    相关资源
    最近更新 更多