FormParser
Relevant source files
The following files were used as context for generating this wiki page:
The FormParser is the primary high-level interface in the python-multipart library. It provides an all-in-one streaming solution for parsing incoming HTTP form data. Based on the provided Content-Type, it automatically instantiates and manages the appropriate underlying parser—whether for multipart/form-data, URL-encoded query strings, or raw octet streams—and routes parsed data to user-defined callbacks.
Sources: python_multipart/multipart.py:1159-1175, python_multipart/init.py:24-34
Architecture and Design
The FormParser acts as a wrapper and coordinator. It handles the lifecycle of the parsing process, including configuration management, parser selection, and the instantiation of Field or File objects to represent the parsed content.
Component Interaction
When a FormParser is initialized, it determines which specialized parser to use:
- MultipartParser: For
multipart/form-data. - QuerystringParser: For
application/x-www-form-urlencodedorapplication/x-url-encoded. - OctetStreamParser: For
application/octet-stream.
The following diagram illustrates the initialization and data flow of the FormParser:
The FormParser receives raw bytes via the write() method and forwards them to the selected internal parser.
Sources: python_multipart/multipart.py:1200-1365, python_multipart/multipart.py:1381-1393
Configuration
The FormParser uses a centralized configuration dictionary to control file handling, memory limits, and security constraints.
| Option | Type | Default | Description |
|---|---|---|---|
MAX_BODY_SIZE | float | inf | Maximum size of the entire request body. |
MAX_HEADER_COUNT | int | 8 | Max headers allowed per multipart part. |
MAX_HEADER_SIZE | int | 4224 | Max size of a single header line. |
MAX_MEMORY_FILE_SIZE | int | 1 MiB | Threshold before an in-memory file is flushed to disk. |
UPLOAD_DIR | str/bytes | None | Directory for temporary files. |
UPLOAD_DELETE_TMP | bool | True | Whether to delete temp files automatically. |
UPLOAD_KEEP_FILENAME | bool | False | Use the original filename instead of a random one. |
UPLOAD_ERROR_ON_BAD_CTE | bool | False | Raise error on unknown Content-Transfer-Encoding. |
Sources: python_multipart/multipart.py:1178-1188, python_multipart/multipart.py:101-105
Data Handling Logic
Field and File Creation
As data is processed, the FormParser defines internal callbacks that translate low-level parser events into domain objects:
- Field: Represents text inputs. It buffers data and provides a
.valueproperty. - File: Represents file uploads. It can start in memory and transition to disk if the size exceeds
MAX_MEMORY_FILE_SIZE.
In multipart parsing, the FormParser specifically looks for the name parameter in the Content-Disposition header; if missing, it raises a FormParserError.
Sources: python_multipart/multipart.py:1275-1310, python_multipart/multipart.py:1330-1350, tests/test_multipart.py:1078-1090
Content-Transfer-Encoding
The FormParser supports automatic decoding for multipart parts. It handles the following encodings:
base64: UsesBase64Decoder.quoted-printable: UsesQuotedPrintableDecoder.7bit,8bit,binary: Written directly to the target object.
Sources: python_multipart/multipart.py:1315-1335, CHANGELOG.md:38
Helper Functions
The library provides two primary helper functions to simplify FormParser usage.
create_form_parser
This function instantiates a FormParser by extracting the Content-Type and boundary directly from a headers dictionary.
Sources: python_multipart/multipart.py:1414-1440
parse_form
A utility for blocking/synchronous execution that reads from an input stream and feeds the parser in chunks (default 1 MiB).
def parse_form(headers, input_stream, on_field, on_file, chunk_size=1048576):
parser = create_form_parser(headers, on_field, on_file)
# Reads from input_stream and calls parser.write()
# Calls parser.finalize() at the end
Sources: python_multipart/multipart.py:1443-1483, fuzz/fuzz_form.py:20-40
Lifecycle Management
To ensure all data is processed and resources are freed, the parser lifecycle must be followed:
- write(data): Ingests chunks of bytes. Returns the number of bytes processed.
- finalize(): Signals the end of the data stream. Triggers the final
on_endcallback and ensures allField/Fileobjects are finalized. - close(): Closes the underlying parser and any open file handles.
Sources: python_multipart/multipart.py:1395-1411, tests/test_multipart.py:1052-1061
Summary
The FormParser serves as the orchestration layer of python-multipart, abstracting the complexity of different HTTP body formats. By utilizing a callback-based architecture and configurable streaming, it enables efficient handling of large-scale form submissions and file uploads with minimal memory overhead.
Sources: python_multipart/multipart.py:1159-1175, README.md:1-15