OLD | NEW |
(Empty) | |
| 1 from __future__ import absolute_import |
| 2 import email.utils |
| 3 import mimetypes |
| 4 |
| 5 from .packages import six |
| 6 |
| 7 |
| 8 def guess_content_type(filename, default='application/octet-stream'): |
| 9 """ |
| 10 Guess the "Content-Type" of a file. |
| 11 |
| 12 :param filename: |
| 13 The filename to guess the "Content-Type" of using :mod:`mimetypes`. |
| 14 :param default: |
| 15 If no "Content-Type" can be guessed, default to `default`. |
| 16 """ |
| 17 if filename: |
| 18 return mimetypes.guess_type(filename)[0] or default |
| 19 return default |
| 20 |
| 21 |
| 22 def format_header_param(name, value): |
| 23 """ |
| 24 Helper function to format and quote a single header parameter. |
| 25 |
| 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. |
| 29 |
| 30 :param name: |
| 31 The name of the parameter, a string expected to be ASCII only. |
| 32 :param value: |
| 33 The value of the parameter, provided as a unicode string. |
| 34 """ |
| 35 if not any(ch in value for ch in '"\\\r\n'): |
| 36 result = '%s="%s"' % (name, value) |
| 37 try: |
| 38 result.encode('ascii') |
| 39 except (UnicodeEncodeError, UnicodeDecodeError): |
| 40 pass |
| 41 else: |
| 42 return result |
| 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) |
| 47 return value |
| 48 |
| 49 |
| 50 class RequestField(object): |
| 51 """ |
| 52 A data container for request body parameters. |
| 53 |
| 54 :param name: |
| 55 The name of this request field. |
| 56 :param data: |
| 57 The data/value body. |
| 58 :param filename: |
| 59 An optional filename of the request field. |
| 60 :param headers: |
| 61 An optional dict-like object of headers to initially use for the field. |
| 62 """ |
| 63 def __init__(self, name, data, filename=None, headers=None): |
| 64 self._name = name |
| 65 self._filename = filename |
| 66 self.data = data |
| 67 self.headers = {} |
| 68 if headers: |
| 69 self.headers = dict(headers) |
| 70 |
| 71 @classmethod |
| 72 def from_tuples(cls, fieldname, value): |
| 73 """ |
| 74 A :class:`~urllib3.fields.RequestField` factory from old-style tuple par
ameters. |
| 75 |
| 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. |
| 79 For example:: |
| 80 |
| 81 'foo': 'bar', |
| 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', |
| 86 |
| 87 Field names and filenames must be unicode. |
| 88 """ |
| 89 if isinstance(value, tuple): |
| 90 if len(value) == 3: |
| 91 filename, data, content_type = value |
| 92 else: |
| 93 filename, data = value |
| 94 content_type = guess_content_type(filename) |
| 95 else: |
| 96 filename = None |
| 97 content_type = None |
| 98 data = value |
| 99 |
| 100 request_param = cls(fieldname, data, filename=filename) |
| 101 request_param.make_multipart(content_type=content_type) |
| 102 |
| 103 return request_param |
| 104 |
| 105 def _render_part(self, name, value): |
| 106 """ |
| 107 Overridable helper function to format a single header parameter. |
| 108 |
| 109 :param name: |
| 110 The name of the parameter, a string expected to be ASCII only. |
| 111 :param value: |
| 112 The value of the parameter, provided as a unicode string. |
| 113 """ |
| 114 return format_header_param(name, value) |
| 115 |
| 116 def _render_parts(self, header_parts): |
| 117 """ |
| 118 Helper function to format and quote a single header. |
| 119 |
| 120 Useful for single headers that are composed of multiple items. E.g., |
| 121 'Content-Disposition' fields. |
| 122 |
| 123 :param header_parts: |
| 124 A sequence of (k, v) typles or a :class:`dict` of (k, v) to format |
| 125 as `k1="v1"; k2="v2"; ...`. |
| 126 """ |
| 127 parts = [] |
| 128 iterable = header_parts |
| 129 if isinstance(header_parts, dict): |
| 130 iterable = header_parts.items() |
| 131 |
| 132 for name, value in iterable: |
| 133 if value is not None: |
| 134 parts.append(self._render_part(name, value)) |
| 135 |
| 136 return '; '.join(parts) |
| 137 |
| 138 def render_headers(self): |
| 139 """ |
| 140 Renders the headers for this request field. |
| 141 """ |
| 142 lines = [] |
| 143 |
| 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])) |
| 148 |
| 149 for header_name, header_value in self.headers.items(): |
| 150 if header_name not in sort_keys: |
| 151 if header_value: |
| 152 lines.append('%s: %s' % (header_name, header_value)) |
| 153 |
| 154 lines.append('\r\n') |
| 155 return '\r\n'.join(lines) |
| 156 |
| 157 def make_multipart(self, content_disposition=None, content_type=None, |
| 158 content_location=None): |
| 159 """ |
| 160 Makes this request field into a multipart request field. |
| 161 |
| 162 This method overrides "Content-Disposition", "Content-Type" and |
| 163 "Content-Location" headers to the request parameter. |
| 164 |
| 165 :param content_type: |
| 166 The 'Content-Type' of the request body. |
| 167 :param content_location: |
| 168 The 'Content-Location' of the request body. |
| 169 |
| 170 """ |
| 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)) |
| 175 ) |
| 176 ]) |
| 177 self.headers['Content-Type'] = content_type |
| 178 self.headers['Content-Location'] = content_location |
OLD | NEW |