cURL对Python的请求(使用multipart / form-data)

时间:2016-05-20 14:48:05

标签: python curl python-requests sesame

我正在尝试翻译此cURL请求:

curl -X POST "endpoint" -H 'Content-Type: multipart/form-data' -F "config=@conf.ttl"

到目前为止,我已经得到了这个:

requests.post(
     endpoint,
     headers={"Content-Type": "multipart/form-data"},
     files={"config": ("conf.ttl", open("conf.ttl", "rb"), "text/turtle")}
)

但它并不像预期的那样有效。我错过了什么?

1 个答案:

答案 0 :(得分:1)

您不应该明确设置“multipart / form-data”。它正在覆盖请求标题集的所有其他部分(“multipart / form-data; boundary = 4b9 ...”,)。无需设置标头,请求将为您执行此操作。您可以在下面的示例中看到请求标头(requests.headers)。你可以看到

idx = np.isfinite(x) & np.isfinite(y)
ab = np.polyfit(x[idx], y[idx], 1)

给出:

import requests
endpoint = "http://httpbin.org/post"
r = requests.post(
     endpoint,
     files={"config": ("conf.ttl", open("conf.ttl", "rb"), "text/turtle")}
)
print r.request.headers
print r.headers
print r.text

带有显式标头的代码会向同一网址发送错误。

{'Content-Length': '259', 'Accept-Encoding': 'gzip, deflate', 'Accept': '*/*', 'User-Agent': 'python-requests/2.10.0', 'Connection': 'keep-alive', 'Content-Type': 'multipart/form-data; boundary=4b99265adcf04931964cb96f48b53a36'}
{'Content-Length': '530', 'Server': 'nginx', 'Connection': 'keep-alive', 'Access-Control-Allow-Credentials': 'true', 'Date': 'Fri, 20 May 2016 20:50:05 GMT', 'Access-Control-Allow-Origin': '*', 'Content-Type': 'application/json'}
{
  "args": {}, 
  "data": "", 
  "files": {
    "config": "curl -X POST \"endpoint\" -H 'Content-Type: multipart/form-data' -F \"config=@conf.ttl\"\n\n"
  }, 
  "form": {}, 
  "headers": {
    "Accept": "*/*", 
    "Accept-Encoding": "gzip, deflate", 
    "Content-Length": "259", 
    "Content-Type": "multipart/form-data; boundary=4b99265adcf04931964cb96f48b53a36", 
    "Host": "httpbin.org", 
    "User-Agent": "python-requests/2.10.0"
  }, 
  "json": null, 
  "origin": "84.92.144.93", 
  "url": "http://httpbin.org/post"
}