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

cURL request to Python (using multipart/form-data)

我正在尝试翻译此 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")}
)

但效果不如预期。我错过了什么?

您不应该明确设置 "multipart/form-data"。它正在覆盖由请求 ("multipart/form-data; boundary=4b9...") 设置的 header 的所有其他部分。无需设置 header,requests 将为您完成。您可以在下面的示例中看到请求 headers (requests.headers)。你可以看到

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"
}

如果您的代码带有显式 header,则会对相同的 URL 产生错误。

{'Content-Length': '259', 'Accept-Encoding': 'gzip, deflate', 'Accept': '*/*', 'User-Agent': 'python-requests/2.10.0', 'Connection': 'keep-alive', 'Content-Type': 'multipart/form-data'}
{'Date': 'Fri, 20 May 2016 20:54:34 GMT', 'Content-Length': '291', 'Content-Type': 'text/html', 'Connection': 'keep-alive', 'Server': 'nginx'}
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<title>500 Internal Server Error</title>
<h1>Internal Server Error</h1>
<p>The server encountered an internal error and was unable to complete your request.  Either the server is overloaded or there is an error in the application.</p>