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