File and Field Classes
Relevant source files
The following files were used as context for generating this wiki page:
The python-multipart library utilizes specialized classes to represent and handle the data parsed from multipart and querystring streams. These classes, primarily Field and File, act as data containers and managers that abstract the complexity of memory management and storage during the streaming process.
The Field class is designed for standard form fields (name-value pairs), while the File class handles uploaded files, providing mechanisms to transition from in-memory storage to on-disk storage based on configurable size thresholds. These classes are typically instantiated and managed by the FormParser.
Sources: python_multipart/multipart.py:175-184, python_multipart/multipart.py:318-344
The Field Class
The Field class represents a parsed form field containing a name and a value. It is designed to handle streaming data via its write and on_data methods, appending byte chunks to an internal list until the field is finalized.
Core Logic and Lifecycle
A Field object transitions through several states: initialization with a name, receiving data chunks, and finalization. During finalization, the accumulated chunks are joined into a single byte string and cached for performance.
The diagram above illustrates the lifecycle of a Field instance from data ingestion to memory cleanup.
Sources: python_multipart/multipart.py:204-245
Key Methods and Properties
| Element | Type | Description |
|---|---|---|
from_value | Class Method | Helper to create, write, and finalize a field in one call. |
write(data) | Method | Appends bytes to the internal value storage. |
finalize() | Method | Triggers on_end to join byte chunks and cache the value. |
set_none() | Method | Explicitly sets the field value to None for bare keys (e.g., foo&bar). |
field_name | Property | Returns the field name as bytes. |
value | Property | Returns the full field value (joined bytes or None). |
content_type | Property | Returns the MIME type associated with the field, if any. |
Sources: python_multipart/multipart.py:204-315, CHANGELOG.md:21-22
The File Class
The File class manages uploaded file data. Its primary responsibility is handling the trade-off between memory usage and disk I/O. It stores data in an io.BytesIO buffer until it exceeds a specified size limit, at which point it "flushes" the content to a temporary file on disk.
Storage Transition Logic
The File class monitors the _bytes_written counter. When this exceeds MAX_MEMORY_FILE_SIZE, the class automatically initiates a transition from memory to disk.
This flow represents the automated transition from BytesIO to a file-on-disk managed by the File class.
Sources: python_multipart/multipart.py:537-558, tests/test_multipart.py:151-168
Configuration Options
The File class behavior is heavily influenced by the FileConfig dictionary.
| Option | Type | Default | Description |
|---|---|---|---|
UPLOAD_DIR | str/bytes | None | Directory for disk storage. |
UPLOAD_DELETE_TMP | bool | True | Whether to delete temp files on close. |
UPLOAD_KEEP_FILENAME | bool | False | Use the original filename instead of a random one. |
UPLOAD_KEEP_EXTENSIONS | bool | False | Preserve the original file extension. |
MAX_MEMORY_FILE_SIZE | int | 1 MiB | Threshold for switching to disk storage. |
Sources: python_multipart/multipart.py:322-332, python_multipart/multipart.py:917-927
Filename Handling and Security
The class extracts the basename using os.path.basename to prevent directory traversal attacks during the upload process. It maintains three distinct filename properties:
file_name: The original name provided in the upload request._file_base: The base name of the original file.actual_file_name: The path or name of the file as it exists on the local filesystem.
Sources: python_multipart/multipart.py:350-361, CHANGELOG.md:43-44
Integration with FormParser
The FormParser acts as a factory and orchestrator, instantiating Field and File objects based on the Content-Type and Content-Disposition headers found in the multipart stream.
The sequence shows how FormParser intercepts parser events to manage the lifecycle of Field and File objects.
Sources: python_multipart/multipart.py:1018-1077, tests/test_benchmarks.py:43-56
Callback Execution
In the multipart/form-data context, FormParser captures headers in on_header_end and uses them to determine whether to create a Field or a File once on_headers_finished is triggered.
- Field Creation: Occurs when the
Content-Dispositiondoes not contain afilenameparameter. - File Creation: Occurs when a
filenameparameter is present.
Sources: python_multipart/multipart.py:1040-1065, tests/test_multipart.py:954-972
Summary
The Field and File classes provide a robust abstraction for data handling in python-multipart. By implementing a consistent write/finalize interface, they allow the parsers to stream data efficiently without concerning themselves with the underlying storage medium. The File class specifically provides critical resource management by preventing excessive memory consumption during large file uploads through its configurable thresholding and disk-flushing logic.
Sources: python_multipart/multipart.py:175-184, python_multipart/multipart.py:537-550