Django 6.1.3

4.2 HTTP, routing, and views

File uploads and streaming responses

How does Django stream multipart uploads without exhausting RAM, and what changes inside middleware when a view returns StreamingHttpResponse?

Ordinary web endpoints buffer both halves of HTTP: a small form body fits cleanly in a QueryDict, and an HTML template renders into a single bytes buffer inside HttpResponse. Push past a few megabytes — uploading a high-resolution press photo on "/submit/" or exporting a million-row archive CSV — and buffering either direction in RAM turns one slow client into an out-of-memory worker crash.

Django splits streaming into two symmetric mechanisms: pluggable upload handlers on the way in, and StreamingHttpResponse on the way out. Both solve memory pressure cleanly, and both break assumptions that ordinary middleware relies on.

Streaming uploads: memory vs. temporary disk files

When HttpRequest._load_post_and_files encounters "multipart/form-data", it calls HttpRequest.parse_file_upload, freezes the handler list inside an ImmutableList, and constructs MultiPartParser.

An upload handler is a subclass of FileUploadHandler that receives an incoming upload in 64 KiB chunks (chunk_size = 64 * 2**10) through four hooks: handle_raw_input, new_file, receive_data_chunk, and file_complete. By default, settings.FILE_UPLOAD_HANDLERS installs two handlers in order:

  1. MemoryFileUploadHandler runs first. Inside handle_raw_input, it checks the total upload size (seeking the stream on ASGI’s tempfile.SpooledTemporaryFile when possible, or trusting WSGI’s "CONTENT_LENGTH"). If content_length <= settings.FILE_UPLOAD_MAX_MEMORY_SIZE (2.5 MiB default), it sets activated = True. When new_file fires, it opens an io.BytesIO buffer and raises StopFutureHandlers so no later handler sees the file, returning an InMemoryUploadedFile from file_complete.
  2. When the upload exceeds FILE_UPLOAD_MAX_MEMORY_SIZE, MemoryFileUploadHandler sets activated = False and passes every 64 KiB chunk untouched to TemporaryFileUploadHandler, which creates a TemporaryUploadedFile on disk (FILE_UPLOAD_TEMP_DIR), writes chunks directly to disk as they arrive, rewinds with seek(0), and hands the open file handle back in FILES.

Test that exact threshold live with FILE_UPLOAD_MAX_MEMORY_SIZE = 1024:

Recorded on Django 6.1.3 ch04-routing script
Upload handlers (FILE_UPLOAD_MAX_MEMORY_SIZE) and StreamingHttpResponse lifecycle
  small 512B upload (limit=1024) -> InMemoryUploadedFile size=512 handlers=['MemoryFileUploadHandler', 'TemporaryFileUploadHandler']
  large 2048B upload (limit=1024) -> TemporaryUploadedFile size=2048 handlers=['MemoryFileUploadHandler', 'TemporaryFileUploadHandler']

StreamingHttpResponse: inverting middleware and teardown

On the outbound path, HttpResponse materializes its entire body into a list of bytes (_container) before leaving the view. StreamingHttpResponse sets streaming = True, holds a one-shot iterator (_iterator), and deliberately removes the content and text attributes (AttributeError on access).

Watch what changes inside WSGIHandler when a view returns a StreamingHttpResponse wrapping a three-chunk generator:

Recorded on Django 6.1.3 ch04-routing script
  StreamingHttpResponse WSGI lifecycle:
    01. view creates StreamingHttpResponse (generator not started)
    02. middleware post-view sees streaming=True hasattr(content)=False
    03. start_response status='200 OK'
    04. WSGI server begins iterating response
    05. generator yields chunk 1
    06. generator yields chunk 2
    07. generator yields chunk 3
    08. WSGI server finished iterating (21 bytes), calling resp.close()
    09. signal request_finished sender=WSGIHandler

Trace steps 01 through 09 carefully — every timing assumption from normal views has inverted:

FileResponse subclasses StreamingHttpResponse specifically for open file-like objects: it registers the file’s .close method inside _resource_closers so HttpResponseBase.close always closes it, computes "Content-Length", "Content-Type", and "Content-Disposition" in FileResponse.set_headers, reads in 4 KiB chunks on WSGI (or hands file_to_stream directly to "wsgi.file_wrapper"), and bumps block_size to 64 KiB under ASGIHandler.

The silent memory blowup: sync streams under ASGI (and vice versa)

Look at lines 515–550 of django/http/response.py (StreamingHttpResponse.__iter__ and StreamingHttpResponse.__aiter__). A StreamingHttpResponse accepts either a synchronous iterator (def chunks(): yield ...) or an asynchronous iterator (async def chunks(): yield ...).

What happens if you return a synchronous generator inside StreamingHttpResponse and deploy your application under ASGIHandler (which consumes aiter(response))? Or return an async generator under WSGIHandler (which consumes iter(response))?

Test the sync-generator-under-ASGI case live on Django 6.1.3:

Recorded on Django 6.1.3 ch04-routing script
  sync generator via StreamingHttpResponse.__aiter__ warning: StreamingHttpResponse must consume synchronous iterators in order to serve them asynchronously. Use an asynchronous iterator instead.
    execution order (all chunks buffered before consumer-c1): gen-1 -> gen-2 -> gen-3 -> consumer-c1 -> consumer-c2 -> consumer-c3

Look at that execution order: gen-1 -> gen-2 -> gen-3 -> consumer-c1 -> consumer-c2 -> consumer-c3!

When StreamingHttpResponse.__aiter__ catches TypeError on a synchronous iterator, it emits a Warning and executes await sync_to_async(list)(self.streaming_content) — draining your entire generator into a Python list in memory before sending the first byte to the client! StreamingHttpResponse.__iter__ does the exact mirror image under WSGI for an async generator (async_to_sync(to_list)). A 2 GiB CSV export written as a synchronous generator streams cleanly in 64 KiB slices on Gunicorn (WSGI), then silently OOM-kills your container the afternoon you switch the Dockerfile to Uvicorn (ASGI).

Where uploads and streaming leak

With incoming requests parsed and streaming mechanics clear, we can step directly into the heart of BaseHandler._get_response: how Django compiles "urls.py" into executable matchers, in Compiling URLResolver and path converters.