web.py 3.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. # -*- coding: utf-8 -*-
  2. import urllib2
  3. import itertools, mimetools, mimetypes
  4. import platform
  5. from txclib import get_version
  6. # Helper class to enable urllib2 to handle PUT/DELETE requests as well
  7. class RequestWithMethod(urllib2.Request):
  8. """Workaround for using DELETE with urllib2"""
  9. def __init__(self, url, method, data=None, headers={},
  10. origin_req_host=None, unverifiable=False):
  11. self._method = method
  12. urllib2.Request.__init__(self, url, data=data, headers=headers,
  13. origin_req_host=None, unverifiable=False)
  14. def get_method(self):
  15. return self._method
  16. import urllib
  17. import os, stat
  18. from cStringIO import StringIO
  19. class Callable:
  20. def __init__(self, anycallable):
  21. self.__call__ = anycallable
  22. # Controls how sequences are uncoded. If true, elements may be given multiple
  23. # values by assigning a sequence.
  24. doseq = 1
  25. class MultipartPostHandler(urllib2.BaseHandler):
  26. handler_order = urllib2.HTTPHandler.handler_order - 10 # needs to run first
  27. def http_request(self, request):
  28. data = request.get_data()
  29. if data is not None and type(data) != str:
  30. v_files = []
  31. v_vars = []
  32. try:
  33. for(key, value) in data.items():
  34. if type(value) == file:
  35. v_files.append((key, value))
  36. else:
  37. v_vars.append((key, value))
  38. except TypeError:
  39. systype, value, traceback = sys.exc_info()
  40. raise TypeError, "not a valid non-string sequence or mapping object", traceback
  41. if len(v_files) == 0:
  42. data = urllib.urlencode(v_vars, doseq)
  43. else:
  44. boundary, data = self.multipart_encode(v_vars, v_files)
  45. contenttype = 'multipart/form-data; boundary=%s' % boundary
  46. if(request.has_header('Content-Type')
  47. and request.get_header('Content-Type').find('multipart/form-data') != 0):
  48. print "Replacing %s with %s" % (request.get_header('content-type'), 'multipart/form-data')
  49. request.add_unredirected_header('Content-Type', contenttype)
  50. request.add_data(data)
  51. return request
  52. def multipart_encode(vars, files, boundary = None, buf = None):
  53. if boundary is None:
  54. boundary = mimetools.choose_boundary()
  55. if buf is None:
  56. buf = StringIO()
  57. for(key, value) in vars:
  58. buf.write('--%s\r\n' % boundary)
  59. buf.write('Content-Disposition: form-data; name="%s"' % key)
  60. buf.write('\r\n\r\n' + value + '\r\n')
  61. for(key, fd) in files:
  62. file_size = os.fstat(fd.fileno())[stat.ST_SIZE]
  63. filename = fd.name.split('/')[-1]
  64. contenttype = mimetypes.guess_type(filename)[0] or 'application/octet-stream'
  65. buf.write('--%s\r\n' % boundary)
  66. buf.write('Content-Disposition: form-data; name="%s"; filename="%s"\r\n' % (key, filename))
  67. buf.write('Content-Type: %s\r\n' % contenttype)
  68. # buffer += 'Content-Length: %s\r\n' % file_size
  69. fd.seek(0)
  70. buf.write('\r\n' + fd.read() + '\r\n')
  71. buf.write('--' + boundary + '--\r\n\r\n')
  72. buf = buf.getvalue()
  73. return boundary, buf
  74. multipart_encode = Callable(multipart_encode)
  75. https_request = http_request
  76. def user_agent_identifier():
  77. """Return the user agent for the client."""
  78. client_info = (get_version(), platform.system(), platform.machine())
  79. return "txclient/%s (%s %s)" % client_info