def encode_multipart_formdata(fields, files): """fields is a sequence of (name, value) elements for regular form fields. files is a sequence of (name, filename, value) elements for data to be uploaded as files Return (content_type, body) ready for httplib.HTTP instance """ BOUNDARY = "GlobalNumberOfPiratesDecreasing-GlobalTemperatureIncreasing" CRLF = "\r\n" request = [] for (key, value) in fields: request.extend( [ "--" + BOUNDARY, 'Content-Disposition: form-data; name="%s"' % key, "", value, ] ) for (key, filename, value) in files: request.extend( [ "--" + BOUNDARY, 'Content-Disposition: form-data; name="%s"; filename="%s"' % (key, filename), "Content-Type: %s" % get_content_type(filename), "", value, ] ) request.append("--" + BOUNDARY + "--") request.append("") body = CRLF.join(request) content_type = "multipart/form-data; boundary=%s" % BOUNDARY return content_type, body