| 39 | |
| 40 | |
| 41 | class StreamingFormReader: |
| 42 | |
| 43 | def __init__(self, headers, output_files_path) -> None: |
| 44 | (content_type, content_type_dict) = parse_header(headers.get('Content-Type')) |
| 45 | |
| 46 | content_length = headers.get('Content-Length') |
| 47 | self.max_length = int(content_length) if content_length else 0 |
| 48 | |
| 49 | if content_type != 'multipart/form-data': |
| 50 | raise Exception('Unsupported content type: ' + content_type) |
| 51 | |
| 52 | if 'boundary' not in content_type_dict: |
| 53 | raise Exception('Failed to find boundary in header ' + content_type) |
| 54 | |
| 55 | self._boundary = b'--' + content_type_dict['boundary'].encode('utf-8') |
| 56 | self._fields_separator = b'\r\n' + self._boundary |
| 57 | self._buffer = b'' |
| 58 | self._current_part = None |
| 59 | self._output_files_path = output_files_path |
| 60 | self._read_bytes = 0 |
| 61 | self.values = {} |
| 62 | self.files = {} |
| 63 | |
| 64 | def read(self, chunk): |
| 65 | if self._reached_end(): |
| 66 | return |
| 67 | |
| 68 | self._buffer += chunk |
| 69 | |
| 70 | self._read_bytes += len(chunk) |
| 71 | |
| 72 | if not self._reached_end() and len(self._buffer) < 128: |
| 73 | return |
| 74 | |
| 75 | count = 0 |
| 76 | |
| 77 | while self._buffer and count < 10000: |
| 78 | count += 1 |
| 79 | |
| 80 | if not self._current_part: |
| 81 | if b'\r\n\r\n' not in self._buffer: |
| 82 | break |
| 83 | |
| 84 | if not self._buffer.startswith(self._boundary): |
| 85 | raise Exception('Invalid buffer format: ' + str(self._buffer)) |
| 86 | |
| 87 | part = self._buffer[len(self._fields_separator):] |
| 88 | |
| 89 | (header, self._buffer) = part.split(b'\r\n\r\n', 1) |
| 90 | |
| 91 | self._current_part = _FormDataPart(header, self._output_files_path) |
| 92 | |
| 93 | if self._fields_separator not in self._buffer: |
| 94 | potential_separator_start = self._find_potential_separator_start(self._buffer) |
| 95 | |
| 96 | if potential_separator_start >= 0: |
| 97 | body = self._buffer[:potential_separator_start] |
| 98 | self._buffer = self._buffer[potential_separator_start:] |
no outgoing calls