---
django: 6.1.3 (f16e25dcb9fe55734ba4ea2b00ac34405b7df74a)
---

# 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`** (`django/http/response.py: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` (`django/http/request.py:HttpRequest.parse_file_upload`), freezes the handler list inside an `ImmutableList`, and constructs `MultiPartParser` (`django/http/multipartparser.py:MultiPartParser`).

An **upload handler** is a subclass of `FileUploadHandler` (`django/core/files/uploadhandler.py: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` (`django/core/files/uploadhandler.py: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` (`django/core/files/uploadhandler.py:StopFutureHandlers`) so no later handler sees the file, returning an `InMemoryUploadedFile` (`django/core/files/uploadedfile.py: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` (`django/core/files/uploadhandler.py:TemporaryFileUploadHandler`), which creates a `TemporaryUploadedFile` (`django/core/files/uploadedfile.py: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`:

```text recording=ch04-routing
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']
```

> **Deeper.** You can swap `HttpRequest.upload_handlers` inside a view (for example, to stream uploads directly to object storage or reject oversized files early with `StopUpload`) — *only* before anything touches `POST` or `FILES`. The moment parsing begins, `HttpRequest.upload_handlers` setter raises `AttributeError("You cannot set the upload handlers after the upload has been processed.")`. That is why custom upload-handler views often need `@csrf_exempt` followed by `@csrf_protect` or careful ordering: `CsrfViewMiddleware.process_view` reads `POST` to check `"csrfmiddlewaretoken"`, which triggers upload parsing before your view even starts!

## `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`** (`django/http/response.py: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:

```text recording=ch04-routing
  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:

- **Middleware finishes *before* the generator runs line 1.** In step `02`, every middleware's post-view code (our timing middleware, `SessionMiddleware`, `GZipMiddleware`, `CommonMiddleware`) has already returned, and `start_response` has already committed HTTP `"200 OK"` headers to the wire (step `03`), while the generator has yielded **zero bytes**!
- **Body-inspecting middleware must branch on `streaming`.** `CommonMiddleware` cannot compute `"Content-Length"`, `"ETag"` helpers cannot hash the body, and any custom middleware touching `HttpResponse.content` without checking `streaming` will crash with `AttributeError`.
- **Exceptions inside the generator cannot become `500` HTML pages.** Because `start_response("200 OK", ...)` already ran and every `convert_exception_to_response` wall in the middleware onion has already unwound, an exception raised during step `06` escapes directly into the WSGI/ASGI server, which can only truncate or reset the TCP connection.
- **`request_finished` waits until the final chunk finishes.** `HttpResponseBase.close` (step `08`) and `request_finished` (step `09`) run only after the WSGI/ASGI server exhausts the stream — meaning database connections stay checked out (and if the generator holds a DB cursor open, `"ATOMIC_REQUESTS"` has *already committed* before step `05` because `BaseHandler.make_view_atomic` only wraps the view function returning the `StreamingHttpResponse`, not the generator's iteration!).

`FileResponse` (`django/http/response.py: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`:

```text recording=ch04-routing
  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

- **Match iterator mode to server mode.** Under `ASGIHandler`, streaming responses *must* pass an `async def` generator; under `WSGIHandler`, they *must* pass a synchronous generator. Watch your logs for Django's `"must consume ... iterators"` warning as a critical memory bug, not cosmetic noise.
- **Database transactions end before streaming starts.** Wrapping a view in `django.db.transaction.atomic` (`django/db/transaction.py:atomic`) or `"ATOMIC_REQUESTS"` commits as soon as the view *returns* `StreamingHttpResponse` — before the generator fetches row 1. If a streaming export needs snapshot isolation or a server-side cursor, open the transaction *inside* the generator itself.
- **Timing middleware lies about streaming endpoints.** Our newsroom's timing middleware measures the time until `StreamingHttpResponse` is *constructed* (often `< 1 ms`), not the 30 seconds the server spends streaming chunks to a slow client.

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](urlconf.md).
