fields.py 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273
  1. from __future__ import absolute_import
  2. import email.utils
  3. import mimetypes
  4. import re
  5. from .packages import six
  6. def guess_content_type(filename, default='application/octet-stream'):
  7. """
  8. Guess the "Content-Type" of a file.
  9. :param filename:
  10. The filename to guess the "Content-Type" of using :mod:`mimetypes`.
  11. :param default:
  12. If no "Content-Type" can be guessed, default to `default`.
  13. """
  14. if filename:
  15. return mimetypes.guess_type(filename)[0] or default
  16. return default
  17. def format_header_param_rfc2231(name, value):
  18. """
  19. Helper function to format and quote a single header parameter using the
  20. strategy defined in RFC 2231.
  21. Particularly useful for header parameters which might contain
  22. non-ASCII values, like file names. This follows RFC 2388 Section 4.4.
  23. :param name:
  24. The name of the parameter, a string expected to be ASCII only.
  25. :param value:
  26. The value of the parameter, provided as ``bytes`` or `str``.
  27. :ret:
  28. An RFC-2231-formatted unicode string.
  29. """
  30. if isinstance(value, six.binary_type):
  31. value = value.decode("utf-8")
  32. if not any(ch in value for ch in '"\\\r\n'):
  33. result = u'%s="%s"' % (name, value)
  34. try:
  35. result.encode('ascii')
  36. except (UnicodeEncodeError, UnicodeDecodeError):
  37. pass
  38. else:
  39. return result
  40. if not six.PY3: # Python 2:
  41. value = value.encode('utf-8')
  42. # encode_rfc2231 accepts an encoded string and returns an ascii-encoded
  43. # string in Python 2 but accepts and returns unicode strings in Python 3
  44. value = email.utils.encode_rfc2231(value, 'utf-8')
  45. value = '%s*=%s' % (name, value)
  46. if not six.PY3: # Python 2:
  47. value = value.decode('utf-8')
  48. return value
  49. _HTML5_REPLACEMENTS = {
  50. u"\u0022": u"%22",
  51. # Replace "\" with "\\".
  52. u"\u005C": u"\u005C\u005C",
  53. u"\u005C": u"\u005C\u005C",
  54. }
  55. # All control characters from 0x00 to 0x1F *except* 0x1B.
  56. _HTML5_REPLACEMENTS.update({
  57. six.unichr(cc): u"%{:02X}".format(cc)
  58. for cc
  59. in range(0x00, 0x1F+1)
  60. if cc not in (0x1B,)
  61. })
  62. def _replace_multiple(value, needles_and_replacements):
  63. def replacer(match):
  64. return needles_and_replacements[match.group(0)]
  65. pattern = re.compile(
  66. r"|".join([
  67. re.escape(needle) for needle in needles_and_replacements.keys()
  68. ])
  69. )
  70. result = pattern.sub(replacer, value)
  71. return result
  72. def format_header_param_html5(name, value):
  73. """
  74. Helper function to format and quote a single header parameter using the
  75. HTML5 strategy.
  76. Particularly useful for header parameters which might contain
  77. non-ASCII values, like file names. This follows the `HTML5 Working Draft
  78. Section 4.10.22.7`_ and matches the behavior of curl and modern browsers.
  79. .. _HTML5 Working Draft Section 4.10.22.7:
  80. https://w3c.github.io/html/sec-forms.html#multipart-form-data
  81. :param name:
  82. The name of the parameter, a string expected to be ASCII only.
  83. :param value:
  84. The value of the parameter, provided as ``bytes`` or `str``.
  85. :ret:
  86. A unicode string, stripped of troublesome characters.
  87. """
  88. if isinstance(value, six.binary_type):
  89. value = value.decode("utf-8")
  90. value = _replace_multiple(value, _HTML5_REPLACEMENTS)
  91. return u'%s="%s"' % (name, value)
  92. # For backwards-compatibility.
  93. format_header_param = format_header_param_html5
  94. class RequestField(object):
  95. """
  96. A data container for request body parameters.
  97. :param name:
  98. The name of this request field. Must be unicode.
  99. :param data:
  100. The data/value body.
  101. :param filename:
  102. An optional filename of the request field. Must be unicode.
  103. :param headers:
  104. An optional dict-like object of headers to initially use for the field.
  105. :param header_formatter:
  106. An optional callable that is used to encode and format the headers. By
  107. default, this is :func:`format_header_param_html5`.
  108. """
  109. def __init__(
  110. self,
  111. name,
  112. data,
  113. filename=None,
  114. headers=None,
  115. header_formatter=format_header_param_html5):
  116. self._name = name
  117. self._filename = filename
  118. self.data = data
  119. self.headers = {}
  120. if headers:
  121. self.headers = dict(headers)
  122. self.header_formatter = header_formatter
  123. @classmethod
  124. def from_tuples(
  125. cls,
  126. fieldname,
  127. value,
  128. header_formatter=format_header_param_html5):
  129. """
  130. A :class:`~urllib3.fields.RequestField` factory from old-style tuple parameters.
  131. Supports constructing :class:`~urllib3.fields.RequestField` from
  132. parameter of key/value strings AND key/filetuple. A filetuple is a
  133. (filename, data, MIME type) tuple where the MIME type is optional.
  134. For example::
  135. 'foo': 'bar',
  136. 'fakefile': ('foofile.txt', 'contents of foofile'),
  137. 'realfile': ('barfile.txt', open('realfile').read()),
  138. 'typedfile': ('bazfile.bin', open('bazfile').read(), 'image/jpeg'),
  139. 'nonamefile': 'contents of nonamefile field',
  140. Field names and filenames must be unicode.
  141. """
  142. if isinstance(value, tuple):
  143. if len(value) == 3:
  144. filename, data, content_type = value
  145. else:
  146. filename, data = value
  147. content_type = guess_content_type(filename)
  148. else:
  149. filename = None
  150. content_type = None
  151. data = value
  152. request_param = cls(
  153. fieldname, data, filename=filename, header_formatter=header_formatter)
  154. request_param.make_multipart(content_type=content_type)
  155. return request_param
  156. def _render_part(self, name, value):
  157. """
  158. Overridable helper function to format a single header parameter. By
  159. default, this calls ``self.header_formatter``.
  160. :param name:
  161. The name of the parameter, a string expected to be ASCII only.
  162. :param value:
  163. The value of the parameter, provided as a unicode string.
  164. """
  165. return self.header_formatter(name, value)
  166. def _render_parts(self, header_parts):
  167. """
  168. Helper function to format and quote a single header.
  169. Useful for single headers that are composed of multiple items. E.g.,
  170. 'Content-Disposition' fields.
  171. :param header_parts:
  172. A sequence of (k, v) tuples or a :class:`dict` of (k, v) to format
  173. as `k1="v1"; k2="v2"; ...`.
  174. """
  175. parts = []
  176. iterable = header_parts
  177. if isinstance(header_parts, dict):
  178. iterable = header_parts.items()
  179. for name, value in iterable:
  180. if value is not None:
  181. parts.append(self._render_part(name, value))
  182. return u'; '.join(parts)
  183. def render_headers(self):
  184. """
  185. Renders the headers for this request field.
  186. """
  187. lines = []
  188. sort_keys = ['Content-Disposition', 'Content-Type', 'Content-Location']
  189. for sort_key in sort_keys:
  190. if self.headers.get(sort_key, False):
  191. lines.append(u'%s: %s' % (sort_key, self.headers[sort_key]))
  192. for header_name, header_value in self.headers.items():
  193. if header_name not in sort_keys:
  194. if header_value:
  195. lines.append(u'%s: %s' % (header_name, header_value))
  196. lines.append(u'\r\n')
  197. return u'\r\n'.join(lines)
  198. def make_multipart(self, content_disposition=None, content_type=None,
  199. content_location=None):
  200. """
  201. Makes this request field into a multipart request field.
  202. This method overrides "Content-Disposition", "Content-Type" and
  203. "Content-Location" headers to the request parameter.
  204. :param content_type:
  205. The 'Content-Type' of the request body.
  206. :param content_location:
  207. The 'Content-Location' of the request body.
  208. """
  209. self.headers['Content-Disposition'] = content_disposition or u'form-data'
  210. self.headers['Content-Disposition'] += u'; '.join([
  211. u'', self._render_parts(
  212. ((u'name', self._name), (u'filename', self._filename))
  213. )
  214. ])
  215. self.headers['Content-Type'] = content_type
  216. self.headers['Content-Location'] = content_location