Advertisement
Guest User

Untitled

a guest
Nov 24th, 2014
168
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.23 KB | None | 0 0
  1. import re
  2. from urllib.request import urlopen, Request
  3. import os
  4. import mimetypes
  5. import mimetools
  6.  
  7. def get_content_type(filepath):
  8. return mimetypes.guess_type(filepath)[0] or 'application/octet-stream'
  9.  
  10. def encode_multipart_formdata(fields, files=[]):
  11. """
  12. fields is a sequence of (name, value) elements for regular form fields.
  13. files is a sequence of (name, filepath) elements for data to be uploaded as files
  14. Return (content_type, body) ready for httplib.HTTP instance
  15. """
  16. BOUNDARY = mimetools.choose_boundary()
  17. CRLF = 'rn'
  18. L = []
  19. for (key, value) in fields:
  20. L.append('--' + BOUNDARY)
  21. L.append('Content-Disposition: form-data; name="%s"' % key)
  22. L.append('')
  23. L.append(value)
  24. for (key, filepath) in files:
  25. L.append('--' + BOUNDARY)
  26. L.append('Content-Disposition: form-data; name="%s"; filename="%s"' % (key, os.path.basename(filepath)))
  27. L.append('Content-Type: %s' % get_content_type(filepath))
  28. L.append('')
  29. L.append(open(filepath, 'rb').read())
  30. L.append('--' + BOUNDARY + '--')
  31. L.append('')
  32. body = CRLF.join(L)
  33. content_type = 'multipart/form-data; boundary=%s' % BOUNDARY
  34. return content_type, body
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement