Accept a `str` `UPLOAD_DIR` when `UPLOAD_KEEP_FILENAME` is set

Merged
SU
1mo ago
+19-1

Problem

UPLOAD_DIR is documented as str in the File config table and typed str | bytes | None in FileConfig, but a str value only works while UPLOAD_KEEP_FILENAME is off. With UPLOAD_KEEP_FILENAME=True, the first write that crosses MAX_MEMORY_FILE_SIZE raises:

import tempfile
from python_multipart.multipart import File

f = File(
    b"foo.txt",
    config={"UPLOAD_DIR": tempfile.mkdtemp(), "UPLOAD_KEEP_FILENAME": True, "MAX_MEMORY_FILE_SIZE": 1},
)
f.write(b"1234")
# TypeError: Can't mix strings and bytes in path components

On main (212819d):

UPLOAD_DIRUPLOAD_KEEP_FILENAMEresult
strFalseok
bytesTrueok
strTrueTypeError

File._get_disk_file() joins file_dir with the filename, which is always bytes. The temporary-file branch right below already handles both str and bytes directories; the keep-filename branch does not, and the mismatch was hidden behind a # type: ignore[arg-type]. The TypeError is also not an OSError, so it is not turned into a FileError.

The existing tests only pass a bytes UPLOAD_DIR together with UPLOAD_KEEP_FILENAME, so this path was not covered.

Fix

Run the directory through os.fsencode() before joining, which accepts both str and bytes, and drop the type: ignore. Behaviour for bytes directories is unchanged.

Tests

Added test_str_upload_dir_with_keep_filename in tests/test_file.py; it fails with the TypeError above before the change. scripts/test (163 passed, 100% coverage) and scripts/check pass locally on Python 3.11.

Related work

  • #308 (open) is the closest change: it also concerns File spilling to disk, but it fixes an AttributeError when file_name is None by initialising _file_base / _ext in File.__init__. This PR changes a different line (os.path.join in _get_disk_file()) for a different input (str UPLOAD_DIR), and neither fix covers the other case.
  • #304 (merged) only reworded the UPLOAD_KEEP_FILENAME docstring.

I found no issue or PR about this TypeError (searched UPLOAD_DIR, UPLOAD_KEEP_FILENAME, mix strings and bytes, fsencode, _get_disk_file, open and closed).

šŸ¤– Generated with Claude Code