|
| 1 | +from io import SEEK_END |
| 2 | +from typing import Iterator, List, Optional, Tuple, Union |
| 3 | + |
| 4 | +from urllib3.fields import RequestField |
| 5 | +from urllib3.filepost import choose_boundary |
| 6 | + |
| 7 | +from ..internal.utils import ByteStream |
| 8 | + |
| 9 | +CHUNK_SIZE = 64 * 1024 |
| 10 | + |
| 11 | +MultipartField = Tuple[str, Optional[str], Union[str, ByteStream], Optional[str]] |
| 12 | + |
| 13 | + |
| 14 | +class MultipartStream: |
| 15 | + """ |
| 16 | + File-like multipart/form-data body which reads part streams lazily, |
| 17 | + so uploads are sent without buffering whole files in memory. |
| 18 | +
|
| 19 | + Fields are (name, file_name, value, content_type) tuples, where value is |
| 20 | + either a string or a binary stream read from its current position. |
| 21 | + """ |
| 22 | + |
| 23 | + def __init__(self, fields: List[MultipartField]): |
| 24 | + self.boundary = choose_boundary() |
| 25 | + self.content_type = f'multipart/form-data; boundary={self.boundary}' |
| 26 | + self._segments: List[Union[bytes, ByteStream]] = [] |
| 27 | + for name, file_name, value, content_type in fields: |
| 28 | + field = RequestField(name=name, data=b'', filename=file_name) |
| 29 | + field.make_multipart(content_type=content_type) |
| 30 | + self._segments.append( |
| 31 | + f'--{self.boundary}\r\n{field.render_headers()}'.encode('utf-8') |
| 32 | + ) |
| 33 | + self._segments.append( |
| 34 | + value.encode('utf-8') if isinstance(value, str) else value |
| 35 | + ) |
| 36 | + self._segments.append(b'\r\n') |
| 37 | + self._segments.append(f'--{self.boundary}--\r\n'.encode('utf-8')) |
| 38 | + self._index = 0 |
| 39 | + self._offset = 0 |
| 40 | + # set when a part stream ends before its declared size; retrying won't help |
| 41 | + self.size_error: Optional[IOError] = None |
| 42 | + # bytes still to send per stream segment, None when the size is unknown |
| 43 | + self._remaining: List[Optional[int]] = [ |
| 44 | + None if isinstance(segment, bytes) else self._stream_size(segment) |
| 45 | + for segment in self._segments |
| 46 | + ] |
| 47 | + # requests reads `len` to set Content-Length; None makes it fall back |
| 48 | + # to chunked transfer encoding |
| 49 | + self.len = self._compute_length() |
| 50 | + |
| 51 | + @staticmethod |
| 52 | + def _stream_size(stream: ByteStream) -> Optional[int]: |
| 53 | + try: |
| 54 | + if not stream.seekable(): |
| 55 | + return None |
| 56 | + position = stream.tell() |
| 57 | + stream.seek(0, SEEK_END) |
| 58 | + end = stream.tell() |
| 59 | + stream.seek(position) |
| 60 | + # a stream positioned past its end has nothing left to send |
| 61 | + return max(0, end - position) |
| 62 | + except (OSError, AttributeError, TypeError): |
| 63 | + return None |
| 64 | + |
| 65 | + def _compute_length(self) -> Optional[int]: |
| 66 | + total = 0 |
| 67 | + for segment, remaining in zip(self._segments, self._remaining): |
| 68 | + if isinstance(segment, bytes): |
| 69 | + total += len(segment) |
| 70 | + elif remaining is None: |
| 71 | + return None |
| 72 | + else: |
| 73 | + total += remaining |
| 74 | + return total |
| 75 | + |
| 76 | + def read(self, size: Optional[int] = -1) -> bytes: |
| 77 | + if size is None or size < 0: |
| 78 | + return b''.join(iter(lambda: self.read(CHUNK_SIZE), b'')) |
| 79 | + |
| 80 | + chunks = [] |
| 81 | + while size > 0 and self._index < len(self._segments): |
| 82 | + segment = self._segments[self._index] |
| 83 | + if isinstance(segment, bytes): |
| 84 | + chunk = segment[self._offset : self._offset + size] |
| 85 | + self._offset += len(chunk) |
| 86 | + if self._offset >= len(segment): |
| 87 | + self._index += 1 |
| 88 | + self._offset = 0 |
| 89 | + else: |
| 90 | + remaining = self._remaining[self._index] |
| 91 | + if remaining == 0: |
| 92 | + # send exactly the size declared in Content-Length, even if the stream grew |
| 93 | + self._index += 1 |
| 94 | + continue |
| 95 | + chunk = segment.read( |
| 96 | + size if remaining is None else min(size, remaining) |
| 97 | + ) |
| 98 | + if not chunk: |
| 99 | + if remaining is not None: |
| 100 | + self.size_error = IOError( |
| 101 | + f'Multipart stream ended {remaining} bytes before its declared size' |
| 102 | + ) |
| 103 | + raise self.size_error |
| 104 | + self._index += 1 |
| 105 | + continue |
| 106 | + if remaining is not None: |
| 107 | + self._remaining[self._index] = remaining - len(chunk) |
| 108 | + chunks.append(chunk) |
| 109 | + size -= len(chunk) |
| 110 | + return b''.join(chunks) |
| 111 | + |
| 112 | + def __iter__(self) -> Iterator[bytes]: |
| 113 | + return iter(lambda: self.read(CHUNK_SIZE), b'') |
| 114 | + |
| 115 | + def __repr__(self) -> str: |
| 116 | + return f'<MultipartStream boundary={self.boundary}>' |
0 commit comments