| | 15 | def encode_multipart_formdata(files): |
|---|
| | 16 | """ |
|---|
| | 17 | fields is a sequence of (name, value) elements for regular form fields. |
|---|
| | 18 | files is a sequence of (name, filename, value) elements for data to be uploaded as files |
|---|
| | 19 | Return (content_type, body) ready for httplib.HTTP instance |
|---|
| | 20 | """ |
|---|
| | 21 | BOUNDARY = '----------ThIs_Is_tHe_bouNdaRY_$' |
|---|
| | 22 | CRLF = '\r\n' |
|---|
| | 23 | L = [] |
|---|
| | 24 | for (key, filename, value) in files: |
|---|
| | 25 | L.append('--' + BOUNDARY) |
|---|
| | 26 | L.append('Content-Disposition: form-data; name="%s"; filename="%s"' % (key, filename)) |
|---|
| | 27 | L.append('Content-Type: %s' % get_content_type(filename)) |
|---|
| | 28 | L.append('') |
|---|
| | 29 | L.append(value) |
|---|
| | 30 | L.append('--' + BOUNDARY + '--') |
|---|
| | 31 | L.append('') |
|---|
| | 32 | body = CRLF.join(L) |
|---|
| | 33 | content_type = 'multipart/form-data; boundary=%s' % BOUNDARY |
|---|
| | 34 | return content_type, body |
|---|
| | 35 | |
|---|
| | 36 | def get_content_type(filename): |
|---|
| | 37 | return mimetypes.guess_type(filename)[0] or 'application/octet-stream' |
|---|
| | 73 | # encode as multipart form data |
|---|
| | 74 | files=[('file', 'file.txt', contents)] |
|---|
| | 75 | content_type, body = encode_multipart_formdata(files) |
|---|
| | 76 | |
|---|
| | 77 | # post file |
|---|
| | 78 | if self.scheme == 'https': |
|---|
| | 79 | c = httplib.HTTPS('127.0.0.1:%s' % self.PORT) |
|---|
| | 80 | else: |
|---|
| | 81 | c = httplib.HTTP('127.0.0.1:%s' % self.PORT) |
|---|
| | 82 | |
|---|
| | 83 | c.putrequest('POST', '/post_multipart') |
|---|
| | 84 | c.putheader('content-type', content_type) |
|---|
| | 85 | c.putheader('content-length', str(len(body))) |
|---|
| | 86 | c.endheaders() |
|---|
| | 87 | c.send(body) |
|---|
| | 88 | errcode, errmsg, headers = c.getreply() |
|---|
| | 89 | |
|---|
| | 90 | response_body = c.file.read() |
|---|
| | 91 | self.assertEquals(post_md5, response_body) |
|---|
| | 92 | |
|---|