Created
September 23, 2013 05:43
-
-
Save nicky-zs/6666815 to your computer and use it in GitHub Desktop.
Build multipart/form-data with files.
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
#vim: fileencoding=utf-8 | |
import mimetools | |
import itertools | |
class MultiPartForm(object): | |
def __init__(self): | |
self.form_fields = [] | |
self.files = [] | |
self.boundary = mimetools.choose_boundary() | |
def get_content_type(self): | |
return 'multipart/form-data; boundary=%s' % self.boundary | |
def add_field(self, name, value): | |
self.form_fields.append((name, value)) | |
def add_file(self, fieldname, filename, body, mimetype): | |
self.files.append((fieldname, filename, mimetype, body)) | |
def __str__(self): | |
parts = [] | |
part_boundary = '--' + self.boundary | |
parts.extend([ | |
part_boundary, | |
'Content-Disposition: form-data; name="%s"' % name, | |
'', | |
value, | |
] for name, value in self.form_fields) | |
parts.extend([ | |
part_boundary, | |
'Content-Disposition: form-data; name="%s"; filename="%s"'\ | |
% (field_name, filename), | |
'Content-Type: %s' % content_type, | |
'', | |
body, | |
] for field_name, filename, content_type, body in self.files) | |
flattened = list(itertools.chain(*parts)) | |
flattened.append('--' + self.boundary + '--') | |
flattened.append('') | |
return '\r\n'.join(flattened) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment