5

我正在尝试在 python 中使用“请求”进行多部分表单上传。我可以上传文件,但它永远不会加载通常通过 curl 的 -F 标志传递的附加字段。我试图模仿的 curl 命令:

curl -v -u user:password -X POST -F 'properties={"filename":"maurizio.png"}' -F "file=@maurizio.png" 192.168.59.103:8080/testdb/mybucket.files

请求代码为:

url = "http://192.168.59.103:8080/testdb/mybucket.files"
content_type = "multipart/form-data"

params = {"filename":"maurizio.png"}
params["_id"] = "test_hash_1234" 

data = open('maurizio.png','rb').read()

files = {'file': ('maurizio.png',data,content_type,params)}               
request = requests.post(url,files=files,auth=('user','password'))

这个文件被加载到 mongodb 的 restheart api 中。“_id”是数据库用来引用对象的特殊对象 ID。除了文件名等其他文档字段之外,我还需要指定该文档字段。该文件被上传到 Mongo 的名为 gridfs 的 blob 数据存储中。我可以使用 curl 上传数据和附加文档字段,但上面的“请求”代码只上传数据而不是附加文档字段。我需要那些额外的字段来查询。

有人可以帮我将 -F 标志转换为与 python 的 requests 模块等效的东西吗?谢谢!

4

2 回答 2

2

查看手册中的示例

files = {'file': ('report.xls', open('report.xls', 'rb'))}
r = requests.post(url, files=files)

请注意,首先您应该传递文件而不是数据(您不需要read()传递文件的内容,只需要传递文件对象)

于 2015-08-13T00:07:13.483 回答
0

顺便说一句,还有一个Github 存储库,其中显示了一些使用 Python 访问 RESTHeart 的基本示例。

目的是展示如何使用 Python 和requests 库进行简单的 RESTful 调用,请随时贡献您的拉取请求以添加更多案例,或​​者看看现有的测试是否可以帮助您。

于 2015-09-09T13:20:42.663 回答