views:

43

answers:

1

Hi, 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

+1  A: 

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.

Lakshman Prasad
thank you :) I used this "patch" http://fabien.seisen.org/python/urllib2_file/ ;)
patrick