1 from __future__ import absolute_import
5 from .packages import six
8 def guess_content_type(filename, default='application/octet-stream'):
10 Guess the "Content-Type" of a file.
13 The filename to guess the "Content-Type" of using :mod:`mimetypes`.
15 If no "Content-Type" can be guessed, default to `default`.
18 return mimetypes.guess_type(filename)[0] or default
22 def format_header_param(name, value):
24 Helper function to format and quote a single header parameter.
26 Particularly useful for header parameters which might contain
27 non-ASCII values, like file names. This follows RFC 2231, as
28 suggested by RFC 2388 Section 4.4.
31 The name of the parameter, a string expected to be ASCII only.
33 The value of the parameter, provided as a unicode string.
35 if not any(ch in value for ch in '"\\\r\n'):
36 result = '%s="%s"' % (name, value)
38 result.encode('ascii')
39 except (UnicodeEncodeError, UnicodeDecodeError):
43 if not six.PY3 and isinstance(value, six.text_type): # Python 2:
44 value = value.encode('utf-8')
45 value = email.utils.encode_rfc2231(value, 'utf-8')
46 value = '%s*=%s' % (name, value)
50 class RequestField(object):
52 A data container for request body parameters.
55 The name of this request field.
59 An optional filename of the request field.
61 An optional dict-like object of headers to initially use for the field.
63 def __init__(self, name, data, filename=None, headers=None):
65 self._filename = filename
69 self.headers = dict(headers)
72 def from_tuples(cls, fieldname, value):
74 A :class:`~urllib3.fields.RequestField` factory from old-style tuple parameters.
76 Supports constructing :class:`~urllib3.fields.RequestField` from
77 parameter of key/value strings AND key/filetuple. A filetuple is a
78 (filename, data, MIME type) tuple where the MIME type is optional.
82 'fakefile': ('foofile.txt', 'contents of foofile'),
83 'realfile': ('barfile.txt', open('realfile').read()),
84 'typedfile': ('bazfile.bin', open('bazfile').read(), 'image/jpeg'),
85 'nonamefile': 'contents of nonamefile field',
87 Field names and filenames must be unicode.
89 if isinstance(value, tuple):
91 filename, data, content_type = value
93 filename, data = value
94 content_type = guess_content_type(filename)
100 request_param = cls(fieldname, data, filename=filename)
101 request_param.make_multipart(content_type=content_type)
105 def _render_part(self, name, value):
107 Overridable helper function to format a single header parameter.
110 The name of the parameter, a string expected to be ASCII only.
112 The value of the parameter, provided as a unicode string.
114 return format_header_param(name, value)
116 def _render_parts(self, header_parts):
118 Helper function to format and quote a single header.
120 Useful for single headers that are composed of multiple items. E.g.,
121 'Content-Disposition' fields.
124 A sequence of (k, v) typles or a :class:`dict` of (k, v) to format
125 as `k1="v1"; k2="v2"; ...`.
128 iterable = header_parts
129 if isinstance(header_parts, dict):
130 iterable = header_parts.items()
132 for name, value in iterable:
134 parts.append(self._render_part(name, value))
136 return '; '.join(parts)
138 def render_headers(self):
140 Renders the headers for this request field.
144 sort_keys = ['Content-Disposition', 'Content-Type', 'Content-Location']
145 for sort_key in sort_keys:
146 if self.headers.get(sort_key, False):
147 lines.append('%s: %s' % (sort_key, self.headers[sort_key]))
149 for header_name, header_value in self.headers.items():
150 if header_name not in sort_keys:
152 lines.append('%s: %s' % (header_name, header_value))
155 return '\r\n'.join(lines)
157 def make_multipart(self, content_disposition=None, content_type=None,
158 content_location=None):
160 Makes this request field into a multipart request field.
162 This method overrides "Content-Disposition", "Content-Type" and
163 "Content-Location" headers to the request parameter.
166 The 'Content-Type' of the request body.
167 :param content_location:
168 The 'Content-Location' of the request body.
171 self.headers['Content-Disposition'] = content_disposition or 'form-data'
172 self.headers['Content-Disposition'] += '; '.join([
173 '', self._render_parts(
174 (('name', self._name), ('filename', self._filename))
177 self.headers['Content-Type'] = content_type
178 self.headers['Content-Location'] = content_location