fields.py 5.8 KB

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