Architecture Overview
Relevant source files
The following files were used as context for generating this wiki page:
python-multipart is a streaming multipart parser for Python designed to handle large file uploads and complex form data efficiently. Its primary purpose is to process incoming data chunks as they arrive, minimizing memory consumption by avoiding the need to load entire request bodies into RAM.
The architecture is built around a layered parsing strategy. At the lowest level, individual state-machine-based parsers handle specific formats like multipart/form-data, application/x-www-form-urlencoded, and raw octet-stream. These are orchestrated by a high-level FormParser that provides a unified interface for handling various HTTP content types through event-driven callbacks.
Sources: python_multipart/multipart.py:1004-1017, README.md:1-15, pyproject.toml:7-10
Core Parser Hierarchy
The project utilizes a base class inheritance model to provide consistent callback mechanisms across different parsing logic.
Base Components
BaseParser: The root class providing thecallbackandset_callbackmethods used to notify the application of parsing events (e.g., field starts, data chunks, ends).OctetStreamParser: A simplified parser for raw binary streams.QuerystringParser: Implements a state machine for URL-encoded form data.MultipartParser: The most complex component, implementing a granular state machine for RFC 2046 compliant multipart messages.
The following diagram illustrates the class relationships:
State Machine Logic
The MultipartParser and QuerystringParser utilize internal IntEnum states to track progress through a byte stream. This allows the parsers to pause and resume exactly where they left off when new data chunks are written to them.
Multipart States
The MultipartState tracks the lifecycle of a multipart message, including boundaries, headers, and part data.
| State | Description |
|---|---|
START | Initial state looking for the first boundary. |
HEADER_FIELD | Currently parsing a header name (e.g., "Content-Type"). |
HEADER_VALUE | Currently parsing a header value. |
PART_DATA | Currently streaming the body content of a part. |
END | Terminal state reached after the closing boundary. |
Sources: python_multipart/multipart.py:91-105, python_multipart/multipart.py:968-1323
Sequence of Operation
The following sequence diagram shows how data flows from a raw input stream through the parser and into application-level callbacks.
Data Management: Fields and Files
Parsed data is encapsulated into two primary container classes that manage how data is stored (memory vs. disk).
Field Class
Represents simple form fields. It caches data in memory and joins chunks into a single bytestring upon finalization.
Sources: python_multipart/multipart.py:177-185, tests/test_multipart.py:53-70
File Class
Handles uploaded files with automatic overflow logic. If a file exceeds MAX_MEMORY_FILE_SIZE, it is automatically flushed from a BytesIO buffer to a temporary file on disk using shutil.copyfileobj.
| Configuration Option | Default | Description |
|---|---|---|
UPLOAD_DIR | None | Target directory for on-disk storage. |
MAX_MEMORY_FILE_SIZE | 1 MiB | Threshold before moving data to disk. |
UPLOAD_KEEP_FILENAME | False | Whether to use the original filename. |
UPLOAD_DELETE_TMP | True | Deletes the temp file when the object is closed. |
Sources: python_multipart/multipart.py:284-310, python_multipart/multipart.py:465-480, tests/test_multipart.py:112-135
The FormParser Orchestrator
The FormParser acts as a factory and dispatcher. It inspects the Content-Type header and initializes the appropriate sub-parser.
Security and Performance Features
The architecture includes specific safeguards against common web vulnerabilities and performance bottlenecks:
- Boundary Scan Optimization: Uses
bytes.findfor partial boundary tail scans to improve performance on large payloads.
Sources: CHANGELOG.md:8-10, python_multipart/multipart.py:1175-1185 - Header Limits: Implements
MAX_HEADER_COUNT(default 8) andMAX_HEADER_SIZE(default ~4KB) to prevent DoS attacks involving massive headers.
Sources: python_multipart/multipart.py:134-138, python_multipart/multipart.py:1001-1002 - Boundary Length Cap: Boundaries are restricted to a maximum of 256 bytes.
Sources: python_multipart/multipart.py:140-145, python_multipart/multipart.py:925-928 - RFC 2231 Handling:
parse_options_headerincludes robust parsing for encoded parameters in headers to prevent crashes on malformed inputs.
Sources: python_multipart/multipart.py:155-200, CHANGELOG.md:5-6
Conclusion
The architecture of python-multipart is centered on a non-blocking, event-driven model. By separating stream state management (parsers) from data storage (Field/File) and orchestration (FormParser), the library provides a flexible system capable of handling diverse HTTP body formats while maintaining a constant memory profile.