patrick
patrick

Reputation: 6840

Upload a file with rest

I created a rest api using django and piston and I need to create a script that uploads a file to that api.

currently I'm using this code:

import urllib
import urllib2

user = 'patrick'
password = 'my_password'
url = 'http://localhost:8000/api/odl/'

password_manager = urllib2.HTTPPasswordMgrWithDefaultRealm()
password_manager.add_password(
    None, url, user, password
)

auth_handler = urllib2.HTTPBasicAuthHandler(password_manager)

opener = urllib2.build_opener(auth_handler)
urllib2.install_opener(opener)

f = open('test.pdf')

params = {
    'name': 'ODL Name',
}

postData = urllib.urlencode(params)
fh = urllib2.urlopen(url, postData)

When I run this code I can see that params are sent to the api, but I don't know how to send the file (f) to the api :(

Can you help me?

Thanks

Upvotes: 2

Views: 2540

Answers (1)

lprsd
lprsd

Reputation: 87077

You should include content of the file as a part of the POST data and modify the headers of the Request, to tell the server that there is a file in the post.

Upvotes: 1

Related Questions