Streaming Parser Engine
Relevant source files
The following files were used as context for generating this wiki page:
The Streaming Parser Engine is the core component of the python-multipart library, designed to parse incoming HTTP request bodies in a memory-efficient, streaming fashion. It provides a set of low-level parsers for different content types—including multipart form data, URL-encoded querystrings, and octet streams—allowing for the processing of large uploads without loading the entire payload into RAM.
The engine operates on a push-based model where data chunks are written to a parser, which then triggers specific callbacks as it identifies protocol elements (like headers, field names, or file data). This architecture supports high-performance web applications where streaming uploads are critical for handling large files.
Sources: python_multipart/multipart.py:1-55, README.md
Core Architecture
The engine is built around a base class that manages callbacks and several specialized parser implementations that inherit from it.
BaseParser and Callback System
The BaseParser class provides the infrastructure for managing notification and data callbacks. Notification callbacks are called without parameters (e.g., on_part_begin), while data callbacks receive a buffer and integer indexes (data, start, end) to avoid unnecessary string copying.
The diagram shows the inheritance hierarchy where specialized parsers extend the base callback functionality.
Parser Implementations
MultipartParser
The MultipartParser implements a state-machine-based streaming parser for multipart/form-data. It identifies boundaries and headers using a sliding window approach. It supports limits on header counts and sizes to prevent resource exhaustion attacks.
| State | Description |
|---|---|
START | Initial state, skipping leading newlines. |
START_BOUNDARY | Matching the initial boundary. |
HEADER_FIELD | Parsing individual header keys (e.g., Content-Disposition). |
PART_DATA | Streaming the actual body of a multipart part. |
END | Final state after the closing boundary. |
Sources: python_multipart/multipart.py:102-118, python_multipart/multipart.py:756-788
Multipart Data Flow
This flow represents the transition from raw input to specific event callbacks during multipart parsing.
QuerystringParser
Handles application/x-www-form-urlencoded data. It can operate in a strict_parsing mode where it raises QuerystringParseError if a field lacks an equals sign.
Sources: python_multipart/multipart.py:612-632
OctetStreamParser
The simplest parser, used for application/octet-stream. It treats the entire body as a single stream of data, triggering on_start, on_data, and on_end callbacks.
Sources: python_multipart/multipart.py:544-565
FormParser: High-Level Orchestrator
The FormParser acts as a facade that selects the appropriate internal parser based on the Content-Type. It manages the instantiation of Field and File objects and bridges the gap between raw parser events and developer-friendly objects.
Sequence of events showing how FormParser coordinates internal parsers and data storage.
Configuration and Limits
The engine provides several configuration options to control memory usage and security boundaries.
| Option | Type | Default | Description |
|---|---|---|---|
MAX_BODY_SIZE | float | inf | Maximum total bytes to process. |
MAX_MEMORY_FILE_SIZE | int | 1 MiB | Threshold before an in-memory file is flushed to disk. |
MAX_HEADER_COUNT | int | 8 | Max headers allowed per multipart part. |
MAX_HEADER_SIZE | int | 4224 | Max size of a single header line. |
UPLOAD_DIR | str | None | Directory for temporary files. |
Sources: python_multipart/multipart.py:1189-1200, python_multipart/multipart.py:144-150
Data Storage: Fields and Files
Field Object
Used for simple form values. It buffers data and provides a .value property. It can handle None values for flags in a querystring (e.g., ?flag&name=val).
Sources: python_multipart/multipart.py:202-230
File Object
Manages uploaded file data. It starts as a BytesIO in-memory buffer but transparently flushes to a temporary file on disk if the size exceeds MAX_MEMORY_FILE_SIZE. It supports keeping original extensions and handles IE6-specific path bugs during filename parsing.
Sources: python_multipart/multipart.py:321-365, python_multipart/multipart.py:420-450
Error Handling
The engine defines several specific exception types:
MultipartParseError: Raised for malformed multipart boundaries or headers.QuerystringParseError: Raised for invalid URL-encoded data when strict parsing is enabled.FileError: Raised for filesystem issues during file offloading.FormParserError: General errors during high-level form orchestration.
Sources: python_multipart/multipart.py:18-20, tests/test_multipart.py:35-43
Summary
The Streaming Parser Engine is a robust, state-machine driven system that enables efficient HTTP body parsing. By using a tiered architecture of low-level parsers (Multipart, Querystring, OctetStream) coordinated by a high-level FormParser, the library ensures that large data uploads are processed safely and with minimal memory overhead.
Sources: python_multipart/multipart.py:1-1554