Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting 'curl -F' to Python requests

I'm trying to do a multi-part form upload with "requests" in python. I can upload the file, but it never loads the additional fields that are typically passed through the -F flag with curl. The curl command I'm trying to mimic:

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

The requests code is:

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'))

This file is loaded into restheart api for mongodb. The "_id" is a special object id that the database uses to reference the object. I need to specify that document field in additional to other document fields like the filename. The file is uploaded into Mongo's blob datastore called gridfs. I can upload the data and the additional document fields with curl, but the "requests" code above only uploads the data and not the additional document fields. I need those additional fields for querying.

Can somebody help me convert the -F flag into something that equivalent to python's requests module? Thanks!

like image 761
Gary Leong Avatar asked Oct 31 '22 21:10

Gary Leong


1 Answers

Check out the example in the manual:

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

Note that the first you should pass the file and not the data (you don't need to read() the content of your file, you just need to pass the file object)

like image 52
Dekel Avatar answered Nov 15 '22 04:11

Dekel