MultipartParser
Relevant source files
The following files were used as context for generating this wiki page:
The MultipartParser is a streaming parser specifically designed to handle multipart/form-data request bodies. It is a core component of the python-multipart library, providing a low-level, event-driven interface that processes data in chunks. This allows for efficient handling of large file uploads without loading the entire request body into memory.
Within the project architecture, MultipartParser inherits from BaseParser and is typically orchestrated by the FormParser, which manages higher-level abstractions like Field and File objects. It identifies boundaries, parses headers for each part, and emits data through a series of notification and data callbacks.
Sources: python_multipart/multipart.py:734-754, python_multipart/init.py:17-25
Architecture and State Machine
The MultipartParser operates as a finite state machine (FSM). As bytes are written to the parser via the write() method, it transitions between states defined in the MultipartState enumeration to correctly identify boundaries, headers, and part data.
Parser States
The following states manage the lifecycle of a multipart stream:
| State | Description |
|---|---|
START | Initial state, skips leading newlines before the first boundary. |
START_BOUNDARY | Processing the initial boundary of the message. |
HEADER_FIELD_START | Beginning of a new header field name. |
HEADER_FIELD | Consuming characters of a header field. |
HEADER_VALUE_START | Transitions from field name to value, skipping leading spaces. |
HEADER_VALUE | Consuming characters of a header value. |
PART_DATA | Consuming the actual content of a part. |
END_BOUNDARY | Identifying the final closing boundary. |
END | Terminal state; epilogue data is ignored. |
Sources: python_multipart/multipart.py:61-77, python_multipart/multipart.py:840-1088
State Transition Flow
The following diagram illustrates the primary transitions during the parsing of a single part:
The diagram shows the logic flow from initial boundary detection through header parsing to data extraction.
Sources: python_multipart/multipart.py:840-1088
Boundary Detection Logic
The parser uses a specialized search algorithm to identify boundaries. It maintains an index to track partial matches against the boundary string (which includes the leading \r\n--). To optimize performance, it uses data.find() for fast C-level scanning when the index is zero.
- Fast Path: When searching for the start of a boundary, the parser uses
bytes.find()to locate the boundary string within the current chunk. - Partial Matches: If a chunk ends with a partial boundary match, the parser sets marks and uses a look-behind mechanism during the next
write()call to ensure no data is lost or incorrectly emitted. - Validation: Boundaries must not exceed 256 bytes.
Sources: python_multipart/multipart.py:108-112, python_multipart/multipart.py:1010-1040, python_multipart/multipart.py:779-781
Callback System
MultipartParser communicates with the calling code using callbacks. These are categorized into notification callbacks (no arguments) and data callbacks (passing a buffer and offsets).
Supported Callbacks
| Callback | Type | Trigger |
|---|---|---|
on_part_begin | Notification | When a new part boundary is successfully parsed. |
on_header_field | Data | When a portion of a header name (e.g., "Content-Type") is read. |
on_header_value | Data | When a portion of a header value is read. |
on_headers_finished | Notification | When the blank line after headers is reached. |
on_part_data | Data | When raw body data for the current part is processed. |
on_end | Notification | When the final boundary is reached. |
Sources: python_multipart/multipart.py:41-51, python_multipart/multipart.py:736-746
Data Flow Sequence
This sequence shows the standard order of events for a single-part multipart message.
Sources: python_multipart/multipart.py:870-1080, tests/test_multipart.py:1330-1350
Configuration and Limits
The parser includes several security-related limits to prevent Denial of Service (DoS) attacks, such as Resource Exhaustion.
| Parameter | Default | Description |
|---|---|---|
max_size | inf | Total maximum bytes allowed for the entire body. |
max_header_count | 8 | Maximum number of headers allowed per part. |
max_header_size | 4224 | Maximum size of a single header line (4096 + 128). |
boundary | Required | The boundary string used to separate parts. |
Sources: python_multipart/multipart.py:99-105, python_multipart/multipart.py:756-775
Implementation Details
Writing Data
The write(data) method returns the number of bytes processed. If max_size is exceeded, the input data is truncated.
def write(self, data: bytes) -> int:
data_len = len(data)
if (self._current_size + data_len) > self.max_size:
new_size = int(self.max_size - self._current_size)
data_len = new_size
l = 0
try:
l = self._internal_write(data, data_len)
finally:
self._current_size += l
return l
Sources: python_multipart/multipart.py:783-808
Error Handling
The parser raises MultipartParseError when it encounters malformed input, such as:
- Invalid characters in header names (non-token characters).
- Missing expected CR or LF characters in boundaries or headers.
- Exceeding configured header limits.
Sources: python_multipart/multipart.py:813-818, python_multipart/multipart.py:864-866, tests/test_multipart.py:1080-1100
Conclusion
The MultipartParser provides the foundational streaming logic for the library. By utilizing a robust state machine and a non-copying callback architecture, it efficiently handles complex multipart streams while maintaining strict bounds on resource usage through configurable limits and boundary validation.
Summary of Significance:
- Enables memory-efficient processing of large file uploads.
- Provides granular event hooks for custom part handling.
- Enforces RFC-compliant parsing with security constraints.
Sources: python_multipart/multipart.py:734-754, python_multipart/multipart.py:1130-1140