File Storage & Temporary Files
Relevant source files
The following files were used as context for generating this wiki page:
The python-multipart library provides a robust mechanism for handling uploaded files through a hybrid storage approach. It is designed to process streaming data efficiently, minimizing memory consumption by automatically transitioning large file contents from in-memory buffers to persistent disk storage based on configurable thresholds.
This system is encapsulated primarily within the File class, which manages the lifecycle of an uploaded file from initial data reception to finalization and cleanup. It supports various configurations for directory placement, filename preservation, and automatic deletion of temporary resources.
Sources: python_multipart/multipart.py:284-307, README.md:12-14
Architecture and Components
The file storage system is built around the File class and integrated into the broader FormParser workflow.
The File Class
The File class represents an individual uploaded file. It maintains an internal file object (_fileobj) which starts as an io.BytesIO instance. As data is written via the write() or on_data() methods, the class tracks the number of bytes received. When the size exceeds the MAX_MEMORY_FILE_SIZE limit, the class triggers a flush_to_disk() operation to migrate the content to a temporary file on the file system.
Sources: python_multipart/multipart.py:313-356
Data Flow Diagram
The following diagram illustrates the decision logic when new data is received by the file storage component:
This flowchart describes the automatic transition from memory to disk storage based on size constraints.
Sources: python_multipart/multipart.py:518-543
Configuration Options
The behavior of file storage is highly customizable through a FileConfig or FormParserConfig dictionary.
| Option | Type | Default | Description |
|---|---|---|---|
UPLOAD_DIR | str | bytes | None | None | The directory for disk storage. If None, system defaults are used. |
UPLOAD_DELETE_TMP | bool | True | Whether to automatically delete the temporary file upon closing. |
UPLOAD_KEEP_FILENAME | bool | False | If True, saves the file using its original name (sanitized). |
UPLOAD_KEEP_EXTENSIONS | bool | False | Whether to preserve the original file extension on disk. |
MAX_MEMORY_FILE_SIZE | int | 1048576 (1 MiB) | Threshold in bytes before flushing in-memory data to disk. |
Sources: python_multipart/multipart.py:288-297, python_multipart/multipart.py:843-853
Temporary File Management
Disk Migration Logic
The migration from memory to disk is handled by flush_to_disk(). This method performs the following steps:
- Seeks the current in-memory
BytesIOto the beginning. - Opens a new disk-backed file via
_get_disk_file(). - Uses
shutil.copyfileobjto transfer all existing data to the new file. - Updates the internal
_fileobjreference and sets_in_memorytoFalse. - Closes the old in-memory object.
Sources: python_multipart/multipart.py:417-448
File Creation Hierarchy
The creation of disk files follows a specific priority based on configuration:
- Named Storage: If
UPLOAD_DIRandUPLOAD_KEEP_FILENAMEare set, it attempts to open a file directly atos.path.join(UPLOAD_DIR, sanitized_name). - System Temporary Storage: Otherwise, it utilizes
tempfile.NamedTemporaryFilewith specified suffixes and directories.
Sequence of operations during the disk migration process.
Sources: python_multipart/multipart.py:450-501
Security and Sanitization
To prevent directory traversal attacks, the File class performs basic sanitization of the provided file_name. It uses os.path.basename() to strip any directory paths provided in the Content-Disposition header before processing extensions or storing the file.
# python_multipart/multipart.py:350-356
if file_name is not None:
# Extract just the basename to avoid directory traversal
basename = os.path.basename(file_name)
base, ext = os.path.splitext(basename)
self._file_base = base
self._ext = ext
Sources: python_multipart/multipart.py:350-356, CHANGELOG.md:46
Integration with FormParser
In a standard multipart request, the FormParser identifies file parts via the filename parameter in the Content-Disposition header. When a file is detected, it instantiates a File object and routes the incoming stream to it.
- Header Parsing:
parse_options_headerextracts thefilenameandname(field name). - Lifecycle: The parser calls
on_headers_finishedto create theFileinstance, thenon_part_datato write chunks, and finallyon_part_endto callfinalize()on the file. - Completion: Once finalized, the file is passed to the user-provided
on_filecallback.
Sources: python_multipart/multipart.py:985-1015, tests/test_multipart.py:734-754
Summary
The file storage system in python-multipart provides a seamless transition between memory and disk storage. By leveraging Python's tempfile and shutil modules, it ensures that even extremely large uploads can be handled without exhausting server memory, while offering developers control over file persistence and naming conventions through the FileConfig interface.
Sources: python_multipart/multipart.py:284-307, CHANGELOG.md:32