Fix AttributeError for a nameless upload when keeping the extension/filename

CA
3d ago
+36-4

What happens

File.__init__ sets _file_base and _ext only when it is given a filename. An application/octet-stream upload has none (FormParser(..., file_name=None)), so once the data passes MAX_MEMORY_FILE_SIZE and the file moves to disk, _get_disk_file reads an attribute that does not exist:

p = FormParser("application/octet-stream", None, on_file, file_name=None,
               config={"UPLOAD_KEEP_EXTENSIONS": True, "MAX_MEMORY_FILE_SIZE": 10})
p.write(b"x" * 100)   # AttributeError: 'File' object has no attribute '_ext'

With UPLOAD_DIR and UPLOAD_KEEP_FILENAME set, the same upload fails on _file_base instead. The code already marks the case: # TODO: what happens if we don't have a filename?.

The fix

  • Without a filename, _file_base is None and _ext is empty.
  • _get_disk_file keeps the filename only when there is one; otherwise it falls back to a temporary file in UPLOAD_DIR, as it does when UPLOAD_KEEP_FILENAME is off. The TODO is removed.

Tests

Two tests added to tests/test_file.py (keeping the extension without a filename; keeping the filename without one). Both fail on the current code with AttributeError and pass with the fix. Full suite: 163 passed before, 165 after.

🤖 Generated with Claude Code