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