Python: uploading file via HTTP with pyCurl and Requests

Here is a simple way to upload file in Python. You should have PyCurl installed.

import pycurl
from cStringIO import StringIO
filename='test_file'
c = pycurl.Curl()
c.setopt(c.POST, 1)
c.setopt(c.HTTPPOST, [('title', 'test'), (('file', (c.FORM_FILE, filename)))])
c.setopt(c.VERBOSE, 1)
bodyOutput = StringIO()
headersOutput = StringIO()
c.setopt(c.WRITEFUNCTION, bodyOutput.write)
c.setopt(c.URL, "http://upload.example.com" )
c.setopt(c.HEADERFUNCTION, headersOutput.write)
c.perform()
print bodyOutput.getvalue()

Upd.
File upload with Requests by Kenneth Reitz:

import requests
filename='test_file'
f = open (filename)
r =  requests.post(url='http://upload.example.com', data =  {'title':'test_file},  files =  {'file':f})
print r.status_code
print r.headers

Leave a Reply

Your email address will not be published.