gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 16:34:09 24 4
gpt4 key购买 nike

我正在尝试翻译此 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”。它会覆盖请求设置的 header 的所有其他部分(“multipart/form-data;boundary=4b9...”)。无需设置 header ,请求将为您完成此操作。您可以在下面的示例中看到请求 header (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>

关于python - 对 Python 的 cURL 请求(使用 multipart/form-data),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37349790/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com