-
-
Save pikhovkin/e3d5117e226c2099097cc723e9ca7abf to your computer and use it in GitHub Desktop.
Encode multipart/form-data in python
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
_CONTENT_TYPES = { '.png': 'image/png', '.gif': 'image/gif', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.jpe': 'image/jpeg' } | |
def _encode_multipart(**kw): | |
''' | |
Build a multipart/form-data body with generated random boundary. | |
''' | |
boundary = '----------%s' % hex(int(time.time() * 1000)) | |
data = [] | |
for k, v in kw.iteritems(): | |
data.append('--%s' % boundary) | |
if hasattr(v, 'read'): | |
# file-like object: | |
ext = '' | |
filename = getattr(v, 'name', '') | |
n = filename.rfind('.') | |
if n != (-1): | |
ext = filename[n:].lower() | |
content = v.read() | |
data.append('Content-Disposition: form-data; name="%s"; filename="hidden"' % k) | |
data.append('Content-Length: %d' % len(content)) | |
data.append('Content-Type: %s\r\n' % _guess_content_type(ext)) | |
data.append(content) | |
else: | |
data.append('Content-Disposition: form-data; name="%s"\r\n' % k) | |
data.append(v.encode('utf-8') if isinstance(v, unicode) else v) | |
data.append('--%s--\r\n' % boundary) | |
return '\r\n'.join(data), boundary | |
def _guess_content_type(ext): | |
return _CONTENT_TYPES.get(ext, 'application/octet-stream') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment