encode.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414
  1. """multipart/form-data encoding module
  2. This module provides functions that faciliate encoding name/value pairs
  3. as multipart/form-data suitable for a HTTP POST or PUT request.
  4. multipart/form-data is the standard way to upload files over HTTP"""
  5. __all__ = ['gen_boundary', 'encode_and_quote', 'MultipartParam',
  6. 'encode_string', 'encode_file_header', 'get_body_size', 'get_headers',
  7. 'multipart_encode']
  8. try:
  9. import uuid
  10. def gen_boundary():
  11. """Returns a random string to use as the boundary for a message"""
  12. return uuid.uuid4().hex
  13. except ImportError:
  14. import random, sha
  15. def gen_boundary():
  16. """Returns a random string to use as the boundary for a message"""
  17. bits = random.getrandbits(160)
  18. return sha.new(str(bits)).hexdigest()
  19. import urllib, re, os, mimetypes
  20. try:
  21. from email.header import Header
  22. except ImportError:
  23. # Python 2.4
  24. from email.Header import Header
  25. def encode_and_quote(data):
  26. """If ``data`` is unicode, return urllib.quote_plus(data.encode("utf-8"))
  27. otherwise return urllib.quote_plus(data)"""
  28. if data is None:
  29. return None
  30. if isinstance(data, unicode):
  31. data = data.encode("utf-8")
  32. return urllib.quote_plus(data)
  33. def _strify(s):
  34. """If s is a unicode string, encode it to UTF-8 and return the results,
  35. otherwise return str(s), or None if s is None"""
  36. if s is None:
  37. return None
  38. if isinstance(s, unicode):
  39. return s.encode("utf-8")
  40. return str(s)
  41. class MultipartParam(object):
  42. """Represents a single parameter in a multipart/form-data request
  43. ``name`` is the name of this parameter.
  44. If ``value`` is set, it must be a string or unicode object to use as the
  45. data for this parameter.
  46. If ``filename`` is set, it is what to say that this parameter's filename
  47. is. Note that this does not have to be the actual filename any local file.
  48. If ``filetype`` is set, it is used as the Content-Type for this parameter.
  49. If unset it defaults to "text/plain; charset=utf8"
  50. If ``filesize`` is set, it specifies the length of the file ``fileobj``
  51. If ``fileobj`` is set, it must be a file-like object that supports
  52. .read().
  53. Both ``value`` and ``fileobj`` must not be set, doing so will
  54. raise a ValueError assertion.
  55. If ``fileobj`` is set, and ``filesize`` is not specified, then
  56. the file's size will be determined first by stat'ing ``fileobj``'s
  57. file descriptor, and if that fails, by seeking to the end of the file,
  58. recording the current position as the size, and then by seeking back to the
  59. beginning of the file.
  60. ``cb`` is a callable which will be called from iter_encode with (self,
  61. current, total), representing the current parameter, current amount
  62. transferred, and the total size.
  63. """
  64. def __init__(self, name, value=None, filename=None, filetype=None,
  65. filesize=None, fileobj=None, cb=None):
  66. self.name = Header(name).encode()
  67. self.value = _strify(value)
  68. if filename is None:
  69. self.filename = None
  70. else:
  71. if isinstance(filename, unicode):
  72. # Encode with XML entities
  73. self.filename = filename.encode("ascii", "xmlcharrefreplace")
  74. else:
  75. self.filename = str(filename)
  76. self.filename = self.filename.encode("string_escape").\
  77. replace('"', '\\"')
  78. self.filetype = _strify(filetype)
  79. self.filesize = filesize
  80. self.fileobj = fileobj
  81. self.cb = cb
  82. if self.value is not None and self.fileobj is not None:
  83. raise ValueError("Only one of value or fileobj may be specified")
  84. if fileobj is not None and filesize is None:
  85. # Try and determine the file size
  86. try:
  87. self.filesize = os.fstat(fileobj.fileno()).st_size
  88. except (OSError, AttributeError):
  89. try:
  90. fileobj.seek(0, 2)
  91. self.filesize = fileobj.tell()
  92. fileobj.seek(0)
  93. except:
  94. raise ValueError("Could not determine filesize")
  95. def __cmp__(self, other):
  96. attrs = ['name', 'value', 'filename', 'filetype', 'filesize', 'fileobj']
  97. myattrs = [getattr(self, a) for a in attrs]
  98. oattrs = [getattr(other, a) for a in attrs]
  99. return cmp(myattrs, oattrs)
  100. def reset(self):
  101. if self.fileobj is not None:
  102. self.fileobj.seek(0)
  103. elif self.value is None:
  104. raise ValueError("Don't know how to reset this parameter")
  105. @classmethod
  106. def from_file(cls, paramname, filename):
  107. """Returns a new MultipartParam object constructed from the local
  108. file at ``filename``.
  109. ``filesize`` is determined by os.path.getsize(``filename``)
  110. ``filetype`` is determined by mimetypes.guess_type(``filename``)[0]
  111. ``filename`` is set to os.path.basename(``filename``)
  112. """
  113. return cls(paramname, filename=os.path.basename(filename),
  114. filetype=mimetypes.guess_type(filename)[0],
  115. filesize=os.path.getsize(filename),
  116. fileobj=open(filename, "rb"))
  117. @classmethod
  118. def from_params(cls, params):
  119. """Returns a list of MultipartParam objects from a sequence of
  120. name, value pairs, MultipartParam instances,
  121. or from a mapping of names to values
  122. The values may be strings or file objects, or MultipartParam objects.
  123. MultipartParam object names must match the given names in the
  124. name,value pairs or mapping, if applicable."""
  125. if hasattr(params, 'items'):
  126. params = params.items()
  127. retval = []
  128. for item in params:
  129. if isinstance(item, cls):
  130. retval.append(item)
  131. continue
  132. name, value = item
  133. if isinstance(value, cls):
  134. assert value.name == name
  135. retval.append(value)
  136. continue
  137. if hasattr(value, 'read'):
  138. # Looks like a file object
  139. filename = getattr(value, 'name', None)
  140. if filename is not None:
  141. filetype = mimetypes.guess_type(filename)[0]
  142. else:
  143. filetype = None
  144. retval.append(cls(name=name, filename=filename,
  145. filetype=filetype, fileobj=value))
  146. else:
  147. retval.append(cls(name, value))
  148. return retval
  149. def encode_hdr(self, boundary):
  150. """Returns the header of the encoding of this parameter"""
  151. boundary = encode_and_quote(boundary)
  152. headers = ["--%s" % boundary]
  153. if self.filename:
  154. disposition = 'form-data; name="%s"; filename="%s"' % (self.name,
  155. self.filename)
  156. else:
  157. disposition = 'form-data; name="%s"' % self.name
  158. headers.append("Content-Disposition: %s" % disposition)
  159. if self.filetype:
  160. filetype = self.filetype
  161. else:
  162. filetype = "text/plain; charset=utf-8"
  163. headers.append("Content-Type: %s" % filetype)
  164. headers.append("")
  165. headers.append("")
  166. return "\r\n".join(headers)
  167. def encode(self, boundary):
  168. """Returns the string encoding of this parameter"""
  169. if self.value is None:
  170. value = self.fileobj.read()
  171. else:
  172. value = self.value
  173. if re.search("^--%s$" % re.escape(boundary), value, re.M):
  174. raise ValueError("boundary found in encoded string")
  175. return "%s%s\r\n" % (self.encode_hdr(boundary), value)
  176. def iter_encode(self, boundary, blocksize=4096):
  177. """Yields the encoding of this parameter
  178. If self.fileobj is set, then blocks of ``blocksize`` bytes are read and
  179. yielded."""
  180. total = self.get_size(boundary)
  181. current = 0
  182. if self.value is not None:
  183. block = self.encode(boundary)
  184. current += len(block)
  185. yield block
  186. if self.cb:
  187. self.cb(self, current, total)
  188. else:
  189. block = self.encode_hdr(boundary)
  190. current += len(block)
  191. yield block
  192. if self.cb:
  193. self.cb(self, current, total)
  194. last_block = ""
  195. encoded_boundary = "--%s" % encode_and_quote(boundary)
  196. boundary_exp = re.compile("^%s$" % re.escape(encoded_boundary),
  197. re.M)
  198. while True:
  199. block = self.fileobj.read(blocksize)
  200. if not block:
  201. current += 2
  202. yield "\r\n"
  203. if self.cb:
  204. self.cb(self, current, total)
  205. break
  206. last_block += block
  207. if boundary_exp.search(last_block):
  208. raise ValueError("boundary found in file data")
  209. last_block = last_block[-len(encoded_boundary)-2:]
  210. current += len(block)
  211. yield block
  212. if self.cb:
  213. self.cb(self, current, total)
  214. def get_size(self, boundary):
  215. """Returns the size in bytes that this param will be when encoded
  216. with the given boundary."""
  217. if self.filesize is not None:
  218. valuesize = self.filesize
  219. else:
  220. valuesize = len(self.value)
  221. return len(self.encode_hdr(boundary)) + 2 + valuesize
  222. def encode_string(boundary, name, value):
  223. """Returns ``name`` and ``value`` encoded as a multipart/form-data
  224. variable. ``boundary`` is the boundary string used throughout
  225. a single request to separate variables."""
  226. return MultipartParam(name, value).encode(boundary)
  227. def encode_file_header(boundary, paramname, filesize, filename=None,
  228. filetype=None):
  229. """Returns the leading data for a multipart/form-data field that contains
  230. file data.
  231. ``boundary`` is the boundary string used throughout a single request to
  232. separate variables.
  233. ``paramname`` is the name of the variable in this request.
  234. ``filesize`` is the size of the file data.
  235. ``filename`` if specified is the filename to give to this field. This
  236. field is only useful to the server for determining the original filename.
  237. ``filetype`` if specified is the MIME type of this file.
  238. The actual file data should be sent after this header has been sent.
  239. """
  240. return MultipartParam(paramname, filesize=filesize, filename=filename,
  241. filetype=filetype).encode_hdr(boundary)
  242. def get_body_size(params, boundary):
  243. """Returns the number of bytes that the multipart/form-data encoding
  244. of ``params`` will be."""
  245. size = sum(p.get_size(boundary) for p in MultipartParam.from_params(params))
  246. return size + len(boundary) + 6
  247. def get_headers(params, boundary):
  248. """Returns a dictionary with Content-Type and Content-Length headers
  249. for the multipart/form-data encoding of ``params``."""
  250. headers = {}
  251. boundary = urllib.quote_plus(boundary)
  252. headers['Content-Type'] = "multipart/form-data; boundary=%s" % boundary
  253. headers['Content-Length'] = str(get_body_size(params, boundary))
  254. return headers
  255. class multipart_yielder:
  256. def __init__(self, params, boundary, cb):
  257. self.params = params
  258. self.boundary = boundary
  259. self.cb = cb
  260. self.i = 0
  261. self.p = None
  262. self.param_iter = None
  263. self.current = 0
  264. self.total = get_body_size(params, boundary)
  265. def __iter__(self):
  266. return self
  267. def next(self):
  268. """generator function to yield multipart/form-data representation
  269. of parameters"""
  270. if self.param_iter is not None:
  271. try:
  272. block = self.param_iter.next()
  273. self.current += len(block)
  274. if self.cb:
  275. self.cb(self.p, self.current, self.total)
  276. return block
  277. except StopIteration:
  278. self.p = None
  279. self.param_iter = None
  280. if self.i is None:
  281. raise StopIteration
  282. elif self.i >= len(self.params):
  283. self.param_iter = None
  284. self.p = None
  285. self.i = None
  286. block = "--%s--\r\n" % self.boundary
  287. self.current += len(block)
  288. if self.cb:
  289. self.cb(self.p, self.current, self.total)
  290. return block
  291. self.p = self.params[self.i]
  292. self.param_iter = self.p.iter_encode(self.boundary)
  293. self.i += 1
  294. return self.next()
  295. def reset(self):
  296. self.i = 0
  297. self.current = 0
  298. for param in self.params:
  299. param.reset()
  300. def multipart_encode(params, boundary=None, cb=None):
  301. """Encode ``params`` as multipart/form-data.
  302. ``params`` should be a sequence of (name, value) pairs or MultipartParam
  303. objects, or a mapping of names to values.
  304. Values are either strings parameter values, or file-like objects to use as
  305. the parameter value. The file-like objects must support .read() and either
  306. .fileno() or both .seek() and .tell().
  307. If ``boundary`` is set, then it as used as the MIME boundary. Otherwise
  308. a randomly generated boundary will be used. In either case, if the
  309. boundary string appears in the parameter values a ValueError will be
  310. raised.
  311. If ``cb`` is set, it should be a callback which will get called as blocks
  312. of data are encoded. It will be called with (param, current, total),
  313. indicating the current parameter being encoded, the current amount encoded,
  314. and the total amount to encode.
  315. Returns a tuple of `datagen`, `headers`, where `datagen` is a
  316. generator that will yield blocks of data that make up the encoded
  317. parameters, and `headers` is a dictionary with the assoicated
  318. Content-Type and Content-Length headers.
  319. Examples:
  320. >>> datagen, headers = multipart_encode( [("key", "value1"), ("key", "value2")] )
  321. >>> s = "".join(datagen)
  322. >>> assert "value2" in s and "value1" in s
  323. >>> p = MultipartParam("key", "value2")
  324. >>> datagen, headers = multipart_encode( [("key", "value1"), p] )
  325. >>> s = "".join(datagen)
  326. >>> assert "value2" in s and "value1" in s
  327. >>> datagen, headers = multipart_encode( {"key": "value1"} )
  328. >>> s = "".join(datagen)
  329. >>> assert "value2" not in s and "value1" in s
  330. """
  331. if boundary is None:
  332. boundary = gen_boundary()
  333. else:
  334. boundary = urllib.quote_plus(boundary)
  335. headers = get_headers(params, boundary)
  336. params = MultipartParam.from_params(params)
  337. return multipart_yielder(params, boundary, cb), headers