5

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 "file=@maurizio.png" 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!

alex
  • 6,818
  • 9
  • 52
  • 103
Gary Leong
  • 199
  • 1
  • 2
  • 12

2 Answers2

2

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)

Dekel
  • 60,707
  • 10
  • 101
  • 129
0

By the way, there is also a Github repository which shows some basic examples of accessing RESTHeart with Python.

The objective was to show how to make simple RESTful calls using Python and the requests library, please, feel free to contribute your pull requests adding more cases, or just have a look at the existing tests if they can help you.

mturatti
  • 651
  • 5
  • 10