---
django: 6.1.3 (f16e25dcb9fe55734ba4ea2b00ac34405b7df74a)
part: The request
promise: A URL maps straight to a view.
contents: request-object, uploads-and-streaming, urlconf, resolving-and-reversing, views-and-decorators, cbv-dispatch, errors-and-debug
---

# HTTP, routing, and views

How Django parses requests and streams responses, compiles URL patterns into regular expressions, reverses them back into paths, and dispatches function and class-based views.

Write a line like `path("stories/<slug:slug>/", StoryDetailView.as_view(), name="story-detail")` in `"urls.py"`, and routing looks like a hash-table lookup from a path string to a Python function. An incoming HTTP request arrives, its parameters appear neatly on `HttpRequest`, the matching view runs, and an HTML response comes back.

Measure what actually happens inside `BaseHandler._get_response` (`django/core/handlers/base.py:BaseHandler._get_response`) on Django `6.1.3` and Python `3.14.8`, and that single mapping splits into two completely different algorithms running in opposite directions.

## Linear scan forward, hash lookup backward

```text figure=url-scaling
URL resolution O(N) scaling vs O(1) reverse() on Django 6.1.3 (Python 3.14.8, 2,000 calls x 5 trials)

matching the last route as route count N grows (microseconds / call):
  routes   static path()   path('<slug>/')   re_path()   warm reverse() [O(1)]   _populate() ms
      10         6.05 us          13.34 us    13.57 us                 5.58 us          0.11 ms
      50        13.15 us          44.11 us    47.15 us                 5.59 us          0.48 ms
     200        40.36 us         164.08 us   177.32 us                 5.64 us          1.90 ms
     500        93.52 us         402.60 us   432.19 us                 5.70 us          4.78 ms

cold first-request URLconf setup on desk/ (5 fresh subprocesses):
  import desk.urls (+ admin.site.urls): 6.22 ms · URLResolver._populate(): 3.50 ms · Total: 9.72 ms

view dispatch overhead (50,000 calls x 5 trials):
  bare FBV: 6.73 us (1.00x) · View.as_view(): 8.97 us (1.33x) · @method_decorator(dispatch): 13.05 us (1.94x)
```

*Every data point is parsed from `ch04-bench`. Matching routes forward is a linear scan where static `path()` runs `4.3x` faster than regex routes at `500` patterns (`93.52 us` vs `402.60 us`), while `reverse()` stays flat at `5.6 us` regardless of URLconf size once `URLResolver._populate` finishes its upfront pass.*

Look at the slope of those four curves. Forward matching (`URLResolver.resolve`) walks `url_patterns` one by one in declaration order — an $O(N)$ linear scan that takes `432.19 us` to reach pattern `500` in a flat list of `re_path` entries. Yet static `path("route-N/")` patterns sit more than four times lower (`93.52 us`), because `RoutePattern.match` (`django/urls/resolvers.py:RoutePattern.match`) skips the regular-expression engine entirely whenever a route declares no path converters and falls back to plain string equality or `str.startswith`.

Meanwhile, `reverse()` runs completely flat — **`5.58 us` at ten routes and `5.70 us` at five hundred** — because `URLResolver._populate` (`django/urls/resolvers.py:URLResolver._populate`) walks the tree once in reverse, feeds every compiled regex through `django.utils.regex_helper.normalize`, and stores inverted format templates inside a hash-backed `MultiValueDict`. The bill for that $O(1)$ speed is paid lazily on the **very first request** a worker serves (`9.72 ms` on our small newsroom project once `"admin.site.urls"` is imported and normalized).

## Inside the core of a request

Between the middleware onion from Chapter 3 and the security checks in Chapter 5 sit five tightly coupled layers inside the centre of every request.

Before routing even begins, `WSGIRequest` and `ASGIRequest` defer almost all HTTP parsing behind `@cached_property` descriptors and immutable `QueryDict` containers, while streaming multipart uploads through pluggable upload handlers so a large file never has to sit in memory at once. Then `URLResolver` lazily imports `"ROOT_URLCONF"`, compiles `path()` routes through path converters into regular expressions, matches incoming paths top-to-bottom into a `ResolverMatch`, and inverts those regexes back into validated, percent-encoded strings on `reverse()`.

Once matched, Django invokes the view — either a decorated function whose wrapper must preserve attributes like `csrf_exempt` and coroutine status, or a class-based view whose `View.as_view` closure allocates a brand-new instance on every request and dispatches through a nine-class Python MRO. Finally, if anything explodes along the way, `ExceptionReporter` and `SafeExceptionReporterFilter` scrub secrets before rendering a debug page, and `HttpResponseBase.close` tears down open upload handles and signals request completion once the last byte leaves the process.

We start with the raw HTTP object every middleware and view receives, in [Building HttpRequest and QueryDict](routing/request-object.md).
