[Chicago] posting html

Carl Karsten carl at personnelware.com
Tue Aug 25 18:25:45 CEST 2009


I am hoping there is a module that does what the 2 funcs below do
(both do the same thing.)  The first shells out to curl, the 2nd blows
up on big files because of data.append(open(filename.read()))

I recoded the 2nd, but because I need to do
h.putheader("content-length", len(data)) I need to calc the len of all
the strings, then add the length of the files. doable, but some ugly
looking code.  I call it python-ick.

I am betting there is something in twisted, but this will be example
code so would prefer to use only standard lib stuff.  but "to use this
install twisted" isn't out of the question.

def CurlUpload(BLIPURL, fields, file):
   cline = "curl -F file=@\"%s\" " % (file)
   for field_name, value in fields.iteritems():
      cline = "%s -F %s=%s " % (cline, field_name, re.escape(value))
   cline = "%s %s" % (cline, BLIPURL)
   result = os.popen(cline, "r")
   return result.read()

def PostMultipart(url, fields, files):
    """@brief Send multi-part HTTP POST request

    @param url POST URL
    @param fields A dict of {field-name: value}
    @param files A list of [(field-name, filename)]
    @return Status, reason, response (see httplib.HTTPConnection.getresponse())
    """
    content_type = 'multipart/form-data; boundary=%s' % MULTIPART_BOUNDARY
    data = []
    for field_name, value in fields.iteritems():
        data.append('--' + MULTIPART_BOUNDARY)
        data.append('Content-Disposition: form-data; name="%s"' % field_name)
        data.append('')
        data.append(value)
    for (field_name, filename) in files:
        data.append('--' + MULTIPART_BOUNDARY)
        data.append('Content-Disposition: form-data; name="%s"; filename="%s"'
                    % (field_name, filename))
        data.append('Content-Type: %s' % GetMimeType(filename))
        data.append('')
        data.append(open(filename).read())
    data.append('--' + MULTIPART_BOUNDARY + '--')
    data.append('')
    data = "\r\n".join(data)

    host, selector = urlparts = urlparse.urlsplit(url)[1:3]
    h = httplib.HTTPConnection(host)
    h.putrequest("POST", selector)
    h.putheader("content-type", content_type)
    h.putheader("content-length", len(data))
    h.endheaders()
    h.send(data)
    response = h.getresponse()
    return response.status, response.reason, response.read()



-- 
Carl K


More information about the Chicago mailing list