Skip to content

Instantly share code, notes, and snippets.

@rhoit
Last active October 4, 2020 22:41
Show Gist options
  • Save rhoit/9573c40feaeb3cf44b4a8544dc0ae2a1 to your computer and use it in GitHub Desktop.
Save rhoit/9573c40feaeb3cf44b4a8544dc0ae2a1 to your computer and use it in GitHub Desktop.
def multipart_encoder(params, files):
boundry = uuid.uuid4().hex
lines = list()
for key, val in params.items():
if val is None: continue
lines.append('--' + boundry)
lines.append('Content-Disposition: form-data; name="%s"'%key)
lines.extend([ '', val ])
for key, uri in files.items():
name = os.path.basename(uri)
mime = mimetypes.guess_type(uri)[0] or 'application/octet-stream'
lines.append('--' + boundry)
lines.append('Content-Disposition: form-data; name="{0}"; filename="{1}"'.format(key, name))
lines.append('Content-Type: ' + mime)
lines.append('')
lines.append(open(uri, 'rb').read())
lines.append('--%s--'%boundry)
body = bytes()
for l in lines:
if isinstance(l, bytes): body += l + b'\r\n'
else: body += bytes(l, encoding='utf8') + b'\r\n'
headers = {
'Content-Type' : 'multipart/form-data; boundary=' + boundry,
}
return headers, body
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment