| 1 | # SPDX-License-Identifier: MIT |
| 2 | from __future__ import absolute_import |
| 3 | import codecs |
| 4 | |
| 5 | from uuid import uuid4 |
| 6 | from io import BytesIO |
| 7 | |
| 8 | from .packages import six |
| 9 | from .packages.six import b |
| 10 | from .fields import RequestField |
| 11 | |
| 12 | writer = codecs.lookup('utf-8')[3] |
| 13 | |
| 14 | |
| 15 | def choose_boundary(): |
| 16 | """ |
| 17 | Our embarrassingly-simple replacement for mimetools.choose_boundary. |
| 18 | """ |
| 19 | return uuid4().hex |
| 20 | |
| 21 | |
| 22 | def iter_field_objects(fields): |
| 23 | """ |
| 24 | Iterate over fields. |
| 25 | |
| 26 | Supports list of (k, v) tuples and dicts, and lists of |
| 27 | :class:`~urllib3.fields.RequestField`. |
| 28 | |
| 29 | """ |
| 30 | if isinstance(fields, dict): |
| 31 | i = six.iteritems(fields) |
| 32 | else: |
| 33 | i = iter(fields) |
| 34 | |
| 35 | for field in i: |
| 36 | if isinstance(field, RequestField): |
| 37 | yield field |
| 38 | else: |
| 39 | yield RequestField.from_tuples(*field) |
| 40 | |
| 41 | |
| 42 | def iter_fields(fields): |
| 43 | """ |
| 44 | .. deprecated:: 1.6 |
| 45 | |
| 46 | Iterate over fields. |
| 47 | |
| 48 | The addition of :class:`~urllib3.fields.RequestField` makes this function |
| 49 | obsolete. Instead, use :func:`iter_field_objects`, which returns |
| 50 | :class:`~urllib3.fields.RequestField` objects. |
| 51 | |
| 52 | Supports list of (k, v) tuples and dicts. |
| 53 | """ |
| 54 | if isinstance(fields, dict): |
| 55 | return ((k, v) for k, v in six.iteritems(fields)) |
| 56 | |
| 57 | return ((k, v) for k, v in fields) |
| 58 | |
| 59 | |
| 60 | def encode_multipart_formdata(fields, boundary=None): |
| 61 | """ |
| 62 | Encode a dictionary of ``fields`` using the multipart/form-data MIME format. |
| 63 | |
| 64 | :param fields: |
| 65 | Dictionary of fields or list of (key, :class:`~urllib3.fields.RequestField`). |
| 66 | |
| 67 | :param boundary: |
| 68 | If not specified, then a random boundary will be generated using |
| 69 | :func:`mimetools.choose_boundary`. |
| 70 | """ |
| 71 | body = BytesIO() |
| 72 | if boundary is None: |
| 73 | boundary = choose_boundary() |
| 74 | |
| 75 | for field in iter_field_objects(fields): |
| 76 | body.write(b('--%s\r\n' % (boundary))) |
| 77 | |
| 78 | writer(body).write(field.render_headers()) |
| 79 | data = field.data |
| 80 | |
| 81 | if isinstance(data, int): |
| 82 | data = str(data) # Backwards compatibility |
| 83 | |
| 84 | if isinstance(data, six.text_type): |
| 85 | writer(body).write(data) |
| 86 | else: |
| 87 | body.write(data) |
| 88 | |
| 89 | body.write(b'\r\n') |
| 90 | |
| 91 | body.write(b('--%s--\r\n' % (boundary))) |
| 92 | |
| 93 | content_type = str('multipart/form-data; boundary=%s' % boundary) |
| 94 | |
| 95 | return body.getvalue(), content_type |