Skip to content

Instantly share code, notes, and snippets.

@rectalogic
Last active August 29, 2015 14:04
Show Gist options
  • Save rectalogic/9a0df27d71cfd8c3d6d5 to your computer and use it in GitHub Desktop.
Save rectalogic/9a0df27d71cfd8c3d6d5 to your computer and use it in GitHub Desktop.
import httplib
import filedata
def post_multipart(host, selector, files):
"""
Post files to an http host as multipart/form-data.
files is a sequence of (name, filename, value) elements for data to be uploaded as files
Return the server's response page.
"""
content_type, body = encode_multipart_formdata(files)
h = httplib.HTTP(host)
h.putrequest('POST', selector)
h.putheader('content-type', content_type)
h.putheader('content-length', str(len(body)))
h.endheaders()
h.send(body)
errcode, errmsg, headers = h.getreply()
#print errcode, errmsg, headers
data = h.file.read()
h.close()
return data
BOUNDARY = '----------ThIs_Is_tHe_bouNdaRY_$'
CRLF = '\r\n'
def encode_multipart_formdata(files):
"""
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
"""
datalines = []
for (key, filename, value) in files:
datalines.append('--' + BOUNDARY)
datalines.append('Content-Disposition: form-data; name="%s"; filename="%s"' % (key, filename))
datalines.append('Content-Type: application/octet-stream')
datalines.append('')
datalines.append(value)
datalines.append('--' + BOUNDARY + '--')
datalines.append('')
body = CRLF.join(datalines)
content_type = 'multipart/form-data; boundary=%s' % BOUNDARY
return content_type, body
if __name__ == "__main__":
files = [("b", "test.m4a", filedata.FILEDATA)]
while True:
try:
body = post_multipart("localhost:9090", "/", files)
print body
except Exception as e:
print e
import time
time.sleep(1)
import string
FILEDATA = "".join(letter * 512 for letter in string.ascii_letters)
import cgi
import filedata
# uwsgi --http :9090 --wsgi-file server.py
# This works: uwsgi --http :9090 --buffer-size 65536 --wsgi-file server.py
def application(environ, start_response):
print("FILEDATA {!r}".format(filedata.FILEDATA[:12]))
start_response('200 OK', [('Content-Type', 'text/html')])
formdata = cgi.FieldStorage(environ=environ, fp=environ['wsgi.input'])
if 'b' in formdata:
file_data = formdata['b'].file.read()
print("data {!r}".format(file_data[:12]))
if file_data != filedata.FILEDATA:
print("ERROR")
return ["ERROR"]
else:
print("SUCCESS")
return ["SUCCESS"]
print("MISSING")
return ["MISSING"]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment