fields.py 5.7 KB

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