Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import httplib
- from cStringIO import StringIO
- from email.mime.multipart import MIMEMultipart
- from email.mime.application import MIMEApplication
- from email.generator import Generator
- from email.encoders import encode_noop
- class FormData(MIMEMultipart):
- '''A simple RFC2388 multipart/form-data implementation.
- Snippet from http://bugs.python.org/issue3244
- '''
- def __init__(self, boundary=None, _subparts=None, **kwargs):
- MIMEMultipart.__init__(self, _subtype='form-data',
- boundary=boundary, _subparts=_subparts, **kwargs)
- def attach(self, subpart):
- if 'MIME-Version' in subpart:
- if subpart['MIME-Version'] != self['MIME-Version']:
- raise ValueError('subpart has incompatible MIME-Version')
- # Note: This isn't strictly necessary, but there is no point in
- # including a MIME-Version header in each subpart.
- del subpart['MIME-Version']
- MIMEMultipart.attach(self, subpart)
- def attach_file(self, subpart, name, filename):
- '''
- Attach a subpart, setting it's Content-Disposition header to "file".
- '''
- name = name.replace('"', '\\"')
- filename = filename.replace('"', '\\"')
- subpart['Content-Disposition'] = \
- 'form-data; name="%s"; filename="%s"' % (name, filename)
- self.attach(subpart)
- def get_request_data(self, trailing_newline=True):
- '''Return the encoded message body.'''
- f = StringIO()
- generator = Generator(f, mangle_from_=False)
- generator._dispatch(self)
- # HTTP needs a trailing newline. Since our return value is likely to
- # be passed directly to an HTTP connection, we might as well add it
- # here.
- if trailing_newline:
- f.write('\n')
- body = f.getvalue()
- headers = dict(self)
- return body, headers
- host = 'localhost'
- port = 8080
- data = 'raw\0data'
- message = FormData()
- attachment = MIMEApplication(data, _encoder=encode_noop)
- message.attach_file(attachment, name='report', filename='bar.bin')
- body, headers = message.get_request_data()
- conn = httplib.HTTPConnection(host, port)
- conn.request('POST', '/', body, headers)
- response = conn.getresponse()
- assert response.status == 200
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement