对Python的cURL请求(使用多部分/表单数据)
我正在尝试转换此卷曲请求:对Python的cURL请求(使用多部分/表单数据),python,curl,python-requests,sesame,Python,Curl,Python Requests,Sesame,我正在尝试转换此卷曲请求: 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",
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")}
)
但它并不像预期的那样有效。我缺少什么?您不应该显式设置“多部分/表单数据”。它将覆盖由请求设置的头的所有其他部分(“多部分/表单数据;边界=4b9…”)。不需要设置头,请求将为您设置头。您可以在下面的示例中看到请求头(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"
}
其中,带有显式标头的代码对同一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>
{'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,2016年5月20日20:54:34 GMT','Content Length':'291','Content Type':'text/html','Connection':'keep alive','Server':'nginx'}
500内部服务器错误
内部服务器错误
服务器遇到内部错误,无法完成您的请求。服务器过载或应用程序中存在错误
不确定,但我相信您希望将'config'
更改为'file'
。这很有效,谢谢。我已经接受了你的回答。它是否在文档中的某个地方说(不需要显式地设置请求头)?不,不是真的,但在示例中没有使用它。