Created
July 8, 2011 22:25
-
-
Save rahulkmr/1072975 to your computer and use it in GitHub Desktop.
Multipart form encoding.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import mimetypes | |
def encode_multipart_formdata(fields=None, files=None): | |
""" | |
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 | |
""" | |
if not (fields or files): | |
return None, None | |
BOUNDARY = '----------ThIs_Is_tHe_bouNdaRY_$' | |
CRLF = '\r\n' | |
L = [] | |
if fields: | |
for (key, value) in fields: | |
L.append('--' + BOUNDARY) | |
L.append('Content-Disposition: form-data; name="%s"' % key) | |
L.append('') | |
L.append(value) | |
if files: | |
for (key, filename, value) in files: | |
L.append('--' + BOUNDARY) | |
L.append('Content-Disposition: form-data; name="%s"; filename="%s"' % (key, filename)) | |
L.append('Content-Type: %s' % get_content_type(filename)) | |
L.append('') | |
L.append(value) | |
L.append('--' + BOUNDARY + '--') | |
L.append('') | |
body = CRLF.join(L) | |
content_type = 'multipart/form-data; boundary=%s' % BOUNDARY | |
return content_type, body | |
def get_content_type(filename): | |
return mimetypes.guess_type(filename)[0] or 'application/octet-stream' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment