I am interested in writing a short python script that uploads a short binary file (.wav / .raw audio) via a POST request to a remote server.
I did this with pycurl, which makes it very simple and leads to a script compression; unfortunately, this also requires the end user to have pycurl installed, which I cannot rely on.
I also saw several examples in other posts that rely only on the main libraries, urllib, urllib2, etc., however they usually seem pretty verbose, which I would also like to avoid.
I am wondering if there are any brief examples that do not require the use of external libraries, and which will be understood by third parties quickly and simply, even if they are not familiar with python.
What I am currently using is as follows:
def upload_wav( wavfile, url=None, **kwargs ):
"""Upload a wav file to the server, return the response."""
class responseCallback:
"""Store the server response."""
def __init__(self):
self.contents=''
def body_callback(self, buf):
self.contents = self.contents + buf
def decode( self ):
self.contents = urllib.unquote(self.contents)
try:
self.contents = simplejson.loads(self.contents)
except:
return self.contents
t = responseCallback()
c = pycurl.Curl()
c.setopt(c.POST,1)
c.setopt(c.WRITEFUNCTION, t.body_callback)
c.setopt(c.URL,url)
postdict = [
('userfile',(c.FORM_FILE,wavfile)),
]
for key in kwargs:
postdict.append( (key,kwargs[key]) )
c.setopt(c.HTTPPOST,postdict)
c.setopt(c.VERBOSE,verbose)
c.perform()
c.close()
t.decode()
return t.contents
This is not accurate, but it gives you a general idea. It works great, for third parties it’s easy to understand, but it requires pycurl.