Django 6.1.3

4.1 HTTP, routing, and views

Building HttpRequest and QueryDict

How do WSGIRequest and ASGIRequest decode headers, cookies, and query strings lazily, and why is QueryDict immutable by default?

Every view receives a single HttpRequest object that appears to hold fully parsed dictionaries for query parameters, form fields, cookies, and headers. Yet constructing a request on every incoming HTTP hit would waste substantial CPU if Django parsed query strings, split cookie headers, and decoded form bodies on endpoints that never touch them.

Open WSGIRequest.__init__ and ASGIRequest.__init__, and you see the opposite strategy: both subclasses skip HttpRequest.__init__ entirely (there is an explicit warning comment on line 63 of django/http/request.py) and leave almost every dictionary unparsed until application code first touches it.

Lazy descriptors on WSGIRequest and ASGIRequest

At construction time, WSGIRequest.__init__ does only the bare minimum needed for routing: it extracts path_info, path, method, "CONTENT_TYPE" parameters (encoding), and wraps "wsgi.input" inside LimitedStream. Everything else waits behind @cached_property or custom properties:

Watch every one of those lazy structures populate on demand in a live trace on Django 6.1.3:

Recorded on Django 6.1.3 ch04-routing script
WSGIRequest lazy parsing, HttpHeaders, QueryDict, and RawPostDataException
  before access: 'GET' in __dict__=False 'COOKIES' in __dict__=False 'headers' in __dict__=False '_post' in __dict__=False
  after access:  'GET' in __dict__=True 'COOKIES' in __dict__=True 'headers' in __dict__=True
  HttpHeaders case/underscore fold: headers['x-desk-token']='press-42' headers['X_DESK_TOKEN']='press-42' cookies={'desk_edition': 'morning', 'theme': 'print'}
  QueryDict multi-value: qd['tag']='council' qd.getlist('tag')=['metro', 'budget', 'council']
  mutating request.GET -> AttributeError: This QueryDict instance is immutable
  after qd.copy(): _mutable=True copy.getlist('tag')=['metro', 'budget', 'council', 'sports'] original=['metro', 'budget', 'council']
  6 fields with limit=5 -> TooManyFieldsSent: The number of GET/POST parameters exceeded settings.DATA_UPLOAD_MAX_NUMBER_FIELDS.
  urlencoded POST then body -> ok len(body)=31 headline='Bridge vote'
  multipart POST then body -> RawPostDataException: You cannot access body after reading from request's data stream
  multipart body then POST -> ok len(body)=110 headline='Bridge vote'

Inside QueryDict: multi-value storage and immutability

HTTP query strings and HTML <select multiple> forms routinely repeat the same parameter name ("tag=metro&tag=budget&tag=council"). A plain Python dict would silently discard earlier values, so Django parses both GET and POST into QueryDict, a subclass of MultiValueDict.

Internally, MultiValueDict stores a Python list for every key ({"tag": ["metro", "budget", "council"]}). Indexing qd["tag"] calls MultiValueDict.__getitem__, which returns list_[-1] — the last value ("council"), matching browser and CGI conventions — while MultiValueDict.getlist returns the full list ["metro", "budget", "council"].

At the end of QueryDict.__init__, Django sets self._mutable = mutable — defaulting to False for every request’s GET and POST. Every mutating method (__setitem__, __delitem__, setlist, appendlist, pop, clear, setdefault) begins by calling QueryDict._assert_mutable, which raises AttributeError("This QueryDict instance is immutable").

Notice line 606 of django/http/request.py as well: QueryDict.__init__ passes max_num_fields=settings.DATA_UPLOAD_MAX_NUMBER_FIELDS (default 1,000) directly to urllib.parse.parse_qsl. If an attacker sends a form or query string with 1,001 keys to provoke CPU or memory exhaustion, QueryDict catches the resulting ValueError and translates it into TooManyFieldsSent, which Chapter 3’s response_for_exception turns into a 400 Bad Request logged to "django.security.TooManyFieldsSent".

The RawPostDataException asymmetry

Look at the last three lines of our recording above, because they expose a nuance almost every developer misremembers.

You are often told: “Never read HttpRequest.body after POST, or Django raises RawPostDataException.” Yet on our "application/x-www-form-urlencoded" POST, reading POST and then reading HttpRequest.body succeeded cleanly! Only the "multipart/form-data" POST crashed with RawPostDataException.

Open lines 462–487 of django/http/request.py to see why:

Where HttpRequest leaks

That multipart streaming path leads straight into how Django handles uploaded files without exhausting RAM — and what flips upside down when a view streams its response back out — in File uploads and streaming responses.