Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import re
- from urllib.request import urlopen, Request
- import os
- import mimetypes
- import mimetools
- def get_content_type(filepath):
- return mimetypes.guess_type(filepath)[0] or 'application/octet-stream'
- def encode_multipart_formdata(fields, files=[]):
- """
- fields is a sequence of (name, value) elements for regular form fields.
- files is a sequence of (name, filepath) elements for data to be uploaded as files
- Return (content_type, body) ready for httplib.HTTP instance
- """
- BOUNDARY = mimetools.choose_boundary()
- CRLF = 'rn'
- L = []
- for (key, value) in fields:
- L.append('--' + BOUNDARY)
- L.append('Content-Disposition: form-data; name="%s"' % key)
- L.append('')
- L.append(value)
- for (key, filepath) in files:
- L.append('--' + BOUNDARY)
- L.append('Content-Disposition: form-data; name="%s"; filename="%s"' % (key, os.path.basename(filepath)))
- L.append('Content-Type: %s' % get_content_type(filepath))
- L.append('')
- L.append(open(filepath, 'rb').read())
- L.append('--' + BOUNDARY + '--')
- L.append('')
- body = CRLF.join(L)
- content_type = 'multipart/form-data; boundary=%s' % BOUNDARY
- return content_type, body
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement