You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

178 lines
5.8 KiB

4 years ago
  1. from __future__ import absolute_import
  2. import email.utils
  3. import mimetypes
  4. from .packages import six
  5. def guess_content_type(filename, default='application/octet-stream'):
  6. """
  7. Guess the "Content-Type" of a file.
  8. :param filename:
  9. The filename to guess the "Content-Type" of using :mod:`mimetypes`.
  10. :param default:
  11. If no "Content-Type" can be guessed, default to `default`.
  12. """
  13. if filename:
  14. return mimetypes.guess_type(filename)[0] or default
  15. return default
  16. def format_header_param(name, value):
  17. """
  18. Helper function to format and quote a single header parameter.
  19. Particularly useful for header parameters which might contain
  20. non-ASCII values, like file names. This follows RFC 2231, as
  21. suggested by RFC 2388 Section 4.4.
  22. :param name:
  23. The name of the parameter, a string expected to be ASCII only.
  24. :param value:
  25. The value of the parameter, provided as a unicode string.
  26. """
  27. if not any(ch in value for ch in '"\\\r\n'):
  28. result = '%s="%s"' % (name, value)
  29. try:
  30. result.encode('ascii')
  31. except (UnicodeEncodeError, UnicodeDecodeError):
  32. pass
  33. else:
  34. return result
  35. if not six.PY3 and isinstance(value, six.text_type): # Python 2:
  36. value = value.encode('utf-8')
  37. value = email.utils.encode_rfc2231(value, 'utf-8')
  38. value = '%s*=%s' % (name, value)
  39. return value
  40. class RequestField(object):
  41. """
  42. A data container for request body parameters.
  43. :param name:
  44. The name of this request field.
  45. :param data:
  46. The data/value body.
  47. :param filename:
  48. An optional filename of the request field.
  49. :param headers:
  50. An optional dict-like object of headers to initially use for the field.
  51. """
  52. def __init__(self, name, data, filename=None, headers=None):
  53. self._name = name
  54. self._filename = filename
  55. self.data = data
  56. self.headers = {}
  57. if headers:
  58. self.headers = dict(headers)
  59. @classmethod
  60. def from_tuples(cls, fieldname, value):
  61. """
  62. A :class:`~urllib3.fields.RequestField` factory from old-style tuple parameters.
  63. Supports constructing :class:`~urllib3.fields.RequestField` from
  64. parameter of key/value strings AND key/filetuple. A filetuple is a
  65. (filename, data, MIME type) tuple where the MIME type is optional.
  66. For example::
  67. 'foo': 'bar',
  68. 'fakefile': ('foofile.txt', 'contents of foofile'),
  69. 'realfile': ('barfile.txt', open('realfile').read()),
  70. 'typedfile': ('bazfile.bin', open('bazfile').read(), 'image/jpeg'),
  71. 'nonamefile': 'contents of nonamefile field',
  72. Field names and filenames must be unicode.
  73. """
  74. if isinstance(value, tuple):
  75. if len(value) == 3:
  76. filename, data, content_type = value
  77. else:
  78. filename, data = value
  79. content_type = guess_content_type(filename)
  80. else:
  81. filename = None
  82. content_type = None
  83. data = value
  84. request_param = cls(fieldname, data, filename=filename)
  85. request_param.make_multipart(content_type=content_type)
  86. return request_param
  87. def _render_part(self, name, value):
  88. """
  89. Overridable helper function to format a single header parameter.
  90. :param name:
  91. The name of the parameter, a string expected to be ASCII only.
  92. :param value:
  93. The value of the parameter, provided as a unicode string.
  94. """
  95. return format_header_param(name, value)
  96. def _render_parts(self, header_parts):
  97. """
  98. Helper function to format and quote a single header.
  99. Useful for single headers that are composed of multiple items. E.g.,
  100. 'Content-Disposition' fields.
  101. :param header_parts:
  102. A sequence of (k, v) tuples or a :class:`dict` of (k, v) to format
  103. as `k1="v1"; k2="v2"; ...`.
  104. """
  105. parts = []
  106. iterable = header_parts
  107. if isinstance(header_parts, dict):
  108. iterable = header_parts.items()
  109. for name, value in iterable:
  110. if value is not None:
  111. parts.append(self._render_part(name, value))
  112. return '; '.join(parts)
  113. def render_headers(self):
  114. """
  115. Renders the headers for this request field.
  116. """
  117. lines = []
  118. sort_keys = ['Content-Disposition', 'Content-Type', 'Content-Location']
  119. for sort_key in sort_keys:
  120. if self.headers.get(sort_key, False):
  121. lines.append('%s: %s' % (sort_key, self.headers[sort_key]))
  122. for header_name, header_value in self.headers.items():
  123. if header_name not in sort_keys:
  124. if header_value:
  125. lines.append('%s: %s' % (header_name, header_value))
  126. lines.append('\r\n')
  127. return '\r\n'.join(lines)
  128. def make_multipart(self, content_disposition=None, content_type=None,
  129. content_location=None):
  130. """
  131. Makes this request field into a multipart request field.
  132. This method overrides "Content-Disposition", "Content-Type" and
  133. "Content-Location" headers to the request parameter.
  134. :param content_type:
  135. The 'Content-Type' of the request body.
  136. :param content_location:
  137. The 'Content-Location' of the request body.
  138. """
  139. self.headers['Content-Disposition'] = content_disposition or 'form-data'
  140. self.headers['Content-Disposition'] += '; '.join([
  141. '', self._render_parts(
  142. (('name', self._name), ('filename', self._filename))
  143. )
  144. ])
  145. self.headers['Content-Type'] = content_type
  146. self.headers['Content-Location'] = content_location