daily pastebin goal
44%
SHARE
TWEET

Untitled

a guest Mar 21st, 2019 53 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import mimetypes
  2. import random
  3. import string
  4.  
  5.  
  6. class MultipartEncoder:
  7.     def __init__(self):
  8.         self.fields = []
  9.         self.files = []
  10.  
  11.     def add_file(self, field_name, path, encoding=None):
  12.         with open(path, 'rb') as f:
  13.             content = f.read()
  14.  
  15.         file_name = path.rsplit('/', 1)
  16.         file_name = file_name[1] if len(file_name) == 2 else file_name[0]
  17.  
  18.         if encoding is None:
  19.             encoding = mimetypes.guess_type(file_name)[0] or 'application/octet-stream'
  20.  
  21.         self.files.append((field_name, file_name, encoding, content))
  22.  
  23.     def add_field(self, name, value):
  24.         self.fields.append((name, value))
  25.  
  26.     def encode(self):
  27.         boundary = ''.join(random.choice(string.ascii_letters + string.digits) for _ in range(16))
  28.         _boundary = b'--' + boundary.encode()
  29.  
  30.         parts = []
  31.  
  32.         for name, value in self.fields:
  33.             parts.extend(
  34.                 [_boundary,
  35.                  b'Content-Disposition: form-data; name="%s"' % name.encode(),
  36.                  b'',
  37.                  value.encode()
  38.                  ]
  39.             )
  40.  
  41.         for field_name, file_name, content_type, body in self.files:
  42.             parts.extend(
  43.                 [_boundary,
  44.                  b'Content-Disposition: form-data; name="%s"; filename="%s"' %
  45.                  (field_name.encode(), file_name.encode()),
  46.                  b'Content-Type: %s' % content_type.encode(),
  47.                  b'',
  48.                  body
  49.                  ]
  50.             )
  51.  
  52.         parts.append(_boundary + b'--')
  53.         parts.append(b'')
  54. return boundary, b'\r\n'.join(parts)
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