SHARE
TWEET

Untitled

a guest Jan 8th, 2011 48 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import httplib
  2. from cStringIO import StringIO
  3. from email.mime.multipart import MIMEMultipart
  4. from email.mime.application import MIMEApplication
  5. from email.generator import Generator
  6. from email.encoders import encode_noop
  7.  
  8.  
  9. class FormData(MIMEMultipart):
  10.     '''A simple RFC2388 multipart/form-data implementation.
  11.  
  12.     Snippet from http://bugs.python.org/issue3244
  13.  
  14.     '''
  15.  
  16.     def __init__(self, boundary=None, _subparts=None, **kwargs):
  17.         MIMEMultipart.__init__(self, _subtype='form-data',
  18.                 boundary=boundary, _subparts=_subparts, **kwargs)
  19.  
  20.     def attach(self, subpart):
  21.         if 'MIME-Version' in subpart:
  22.             if subpart['MIME-Version'] != self['MIME-Version']:
  23.                 raise ValueError('subpart has incompatible MIME-Version')
  24.             # Note: This isn't strictly necessary, but there is no point in
  25.             # including a MIME-Version header in each subpart.
  26.             del subpart['MIME-Version']
  27.         MIMEMultipart.attach(self, subpart)
  28.  
  29.     def attach_file(self, subpart, name, filename):
  30.         '''
  31.         Attach a subpart, setting it's Content-Disposition header to "file".
  32.         '''
  33.         name = name.replace('"', '\\"')
  34.         filename = filename.replace('"', '\\"')
  35.         subpart['Content-Disposition'] = \
  36.                 'form-data; name="%s"; filename="%s"' % (name, filename)
  37.         self.attach(subpart)
  38.  
  39.     def get_request_data(self, trailing_newline=True):
  40.         '''Return the encoded message body.'''
  41.         f = StringIO()
  42.         generator = Generator(f, mangle_from_=False)
  43.         generator._dispatch(self)
  44.         # HTTP needs a trailing newline.  Since our return value is likely to
  45.         # be passed directly to an HTTP connection, we might as well add it
  46.         # here.
  47.         if trailing_newline:
  48.             f.write('\n')
  49.         body = f.getvalue()
  50.         headers = dict(self)
  51.         return body, headers
  52.  
  53. host = 'localhost'
  54. port = 8080
  55. data = 'raw\0data'
  56.  
  57. message = FormData()
  58. attachment = MIMEApplication(data, _encoder=encode_noop)
  59. message.attach_file(attachment, name='report', filename='bar.bin')
  60. body, headers = message.get_request_data()
  61.  
  62. conn = httplib.HTTPConnection(host, port)
  63. conn.request('POST', '/', body, headers)
  64. response = conn.getresponse()
  65. assert response.status == 200
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
Top