Guest User

Untitled

a guest
Feb 19th, 2018
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.19 KB | None | 0 0
  1. import httplib, mimetypes, urlparse
  2.  
  3. def post_multipart(host, selector, fields, files):
  4. """
  5. Post fields and files to an http host as multipart/form-data.
  6. fields is a sequence of (name, value) elements for regular form
  7. fields. files is a sequence of (name, filename, value) elements
  8. for data to be uploaded as files Return the server's response
  9. page.
  10. """
  11. content_type, body = encode_multipart_formdata(fields, files)
  12. h = httplib.HTTP(host)
  13. h.putrequest('POST', selector)
  14. h.putheader('content-type', content_type)
  15. h.putheader('content-length', str(len(body)))
  16. h.endheaders()
  17. h.send(body)
  18. errcode, errmsg, headers = h.getreply()
  19. return h.file.read()
  20.  
  21. def encode_multipart_formdata(fields, files):
  22. """
  23. fields is a sequence of (name, value) elements for regular form
  24. fields. files is a sequence of (name, filename, value) elements
  25. for data to be uploaded as files Return (content_type, body) ready
  26. for httplib.HTTP instance
  27. """
  28. BOUNDARY = '----------ThIs_Is_tHe_bouNdaRY_$'
  29. CRLF = '\r\n'
  30. L = []
  31. for (key, value) in fields:
  32. L.append('--' + BOUNDARY)
  33. L.append('Content-Disposition: form-data; name="%s"' % key)
  34. L.append('')
  35. L.append(value)
  36. for (key, filename, value) in files:
  37. L.append('--' + BOUNDARY)
  38. L.append('Content-Disposition: form-data; name="%s"; filename="%s"' % (key, filename))
  39. L.append('Content-Type: %s' % get_content_type(filename))
  40. L.append('')
  41. L.append(value)
  42. L.append('--' + BOUNDARY + '--')
  43. L.append('')
  44. body = CRLF.join(L)
  45. content_type = 'multipart/form-data; boundary=%s' % BOUNDARY
  46. return content_type, body
  47.  
  48. def get_content_type(filename):
  49. return mimetypes.guess_type(filename)[0] or 'application/octet-stream'
Add Comment
Please, Sign In to add comment