Python POST HTTP binaries using Python: brief non-pycurl examples?

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)),  #wav file to post                                                                                 
        ]
    #If there are extra keyword args add them to the postdict                                                                                  
    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.

+5
source share
5 answers

An encoding is required in the POST file multipart/form-data, and as far as I know, there is no easy way (for example, single-line or something else) to do this with stdlib. But, as you already mentioned, there are many recipes.

, , , , , ? ActiveState :

. MultiPartForm PyMOTW, :

, .

+4

, , pycurl, multipart/form-data, python httplib/urllib2, :

  • Content-Length ()

:

import urllib2, os
image_path = "png\\01.png"
url = 'http://xx.oo.com/webserviceapi/postfile/'
length = os.path.getsize(image_path)
png_data = open(image_path, "rb")
request = urllib2.Request(url, data=png_data)
request.add_header('Cache-Control', 'no-cache')
request.add_header('Content-Length', '%d' % length)
request.add_header('Content-Type', 'image/png')
res = urllib2.urlopen(request).read().strip()
return res

. : http://www.2maomao.com/blog/python-http-post-a-binary-file-using-urllib2/

+2

, , .

, UPSET, , python .. ..

import httplib
class HTTPSConnection(httplib.HTTPSConnection):
def _send_output(self, message_body=None):
    self._buffer.extend(("",""))
    msg = "\r\n".join(self._buffer)
    del self._buffer[:]
    self.send(msg)
    if message_body is not None:
        self.send(message_body)

httplib.HTTPSConnection = HTTPSConnection

HTTP:// HTTPS:// HTTPSConnection HTTPConnection.

, , , , , .

? Python, httplib.py.

+2

How is urlib much more detailed? You build a postdict in much the same way, except that you start with

postdict = [ ('userfile', open(wavfile, 'rb').read()) ]

Once you postdict,

resp = urllib.urlopen(url, urllib.urlencode(postdict))

and then you will get and save resp.read()and possibly unquote and try JSON loading if necessary. Seems like it would actually be shorter! So what am I missing ...?

+1
source

urllib.urlencode does not like certain kinds of binary data.

0
source

All Articles