Created
November 26, 2009 08:41
-
-
Save dopuskh3/243329 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
# multipart post. Original from http://code.activestate.com/recipes/146306/ | |
# use StringIO or fd instead of buffer | |
import mimetools | |
import magic | |
def getMime(content): | |
ms = magic.open(magic.MAGIC_MIME) | |
ms.load() | |
magic_s = ms.buffer(content[:1024]) | |
return magic_s | |
def encode_multipart_formdata(fields, filestreams): | |
""" | |
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 = mimetools.choose_boundary() | |
CRLF = '\r\n' | |
L = [] | |
for (key, value) in fields: | |
L.append('--' + BOUNDARY) | |
L.append('Content-Disposition: form-data; name="%s"' % key) | |
L.append('') | |
L.append(value) | |
for (key, value) in filestreams: | |
L.append('--' + BOUNDARY) | |
L.append('Content-Disposition: form-data; name="%s"; filename="Unspecified"' % (key)) | |
L.append('Content-Type: %s' % getMime(value.read()[:1024])) | |
L.append('') | |
value.seek(0) | |
L.append(value.read()) | |
L.append('--' + BOUNDARY + '--') | |
L.append('') | |
body = CRLF.join(L) | |
content_type = 'multipart/form-data; boundary=%s' % BOUNDARY | |
return content_type, body | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment