简体   繁体   English

使用REST API发布文件:从curl示例到Python代码

[英]Posting a file with a REST API: from a curl example to Python code

I'm trying to code the upload of a file to a web service through a REST API in Python. 我正在尝试通过Python中的REST API对将文件上传到Web服务进行编码。 The service's documentation shows a example using curl as client: 该服务的文档显示了一个使用curl作为客户端的示例:

curl -X POST -H \
-H "Content-Type: multipart/form-data" \
-F "file=filename.ext" \
-F "property1=value1" \
-F "property2=value2" \
-F "property3=value3" \
https://domain/api/endpoint

The difficulty for me is that this syntax doesn't match multipart form-data examples I found, including the requests documentation. 我遇到的困难是该语法与我发现的包含requests文档的多部分表单数据示例不匹配。 I tried this, which doesn't work (rejected by the API): 我尝试了此操作,该操作不起作用(被API拒绝):

import requests

file_data = [
    ("file", "filename.ext"),
    ("property1", "value1"),
    ("property2", "value2"),
    ("property3", "value3"),
]

response = requests.post("https://domain/api/endpoint",
    headers={"Content-Type": "multipart/form-data"}, files=file_data)

With the error: "org.apache.commons.fileupload.FileUploadException: the request was rejected because no multipart boundary was found" 出现错误:“ org.apache.commons.fileupload.FileUploadException:由于未找到多部分边界,请求被拒绝”

Can anybody help in transposing that curl example to proper Python code? 有人可以帮助将curl示例转换为正确的Python代码吗?

Thanks! 谢谢!

R. R.

OK, looks like the web services documentation is wrong, and metadata simply needs to be sent as parameters. 好的,看起来Web服务文档是错误的,只需将元数据作为参数发送。 Moreover, I found in another request that you shouldn't set the header. 此外,我在另一个请求中发现您不应设置标题。 So I was starting from a wrong example. 所以我从一个错误的例子开始。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM