Opened 8 hours ago

#36975 new Uncategorized

SimpleUploadedFile cannot be re-opened

Reported by: Denis Washington Owned by:
Component: Uncategorized Version: 6.0
Severity: Normal Keywords:
Cc: Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

Summary

When a SimpleUploadedFile is closed, it calls close() on the underlying BytesIO, which means that the next call to open() fails (ValueError: I/O operation on closed file.). This is unlike the conceptually similar ContentFile, which explicitly overrides close() to do nothing, avoiding this issue.

How to Reproduce

The following script reproduces the issue:

from django.core.files.base import ContentFile
from django.core.files.uploadedfile import SimpleUploadedFile


def read_twice(file):
    with file.open() as f:
        print(f.read())
    with file.open() as f:
        print(f.read())


# Works as expected
read_twice(ContentFile(b"test data"))

# ValueError: I/O operation on closed file.
read_twice(SimpleUploadedFile("test.txt", b"test data"))

Expected Behavior

SimpleUploadedFile should follow ContentFile in making close() a no-op.

Ideally, the same should be done by its superclass InMemoryUploadedFile, at least if its file is a BytesIO or StringIO. (Skipping closing unconditionally could be risky here because the init method accepts any file-like object in principle.)

Change History (0)

Note: See TracTickets for help on using tickets.
Back to Top