Fixed #8234: Corrected typo in docs/cache.txt
[django.git] / docs / middleware.txt
blobc61bd7c5cc8ac91a2705b0f5929810aae4e4c05f
1 ==========
2 Middleware
3 ==========
5 Middleware is a framework of hooks into Django's request/response processing.
6 It's a light, low-level "plugin" system for globally altering Django's input
7 and/or output.
9 Each middleware component is responsible for doing some specific function. For
10 example, Django includes a middleware component, ``XViewMiddleware``, that adds
11 an ``"X-View"`` HTTP header to every response to a ``HEAD`` request.
13 This document explains all middleware components that come with Django, how to
14 use them, and how to write your own middleware.
16 Activating middleware
17 =====================
19 To activate a middleware component, add it to the ``MIDDLEWARE_CLASSES`` list
20 in your Django settings. In ``MIDDLEWARE_CLASSES``, each middleware component
21 is represented by a string: the full Python path to the middleware's class
22 name. For example, here's the default ``MIDDLEWARE_CLASSES`` created by
23 ``django-admin.py startproject``::
25     MIDDLEWARE_CLASSES = (
26         'django.middleware.common.CommonMiddleware',
27         'django.contrib.sessions.middleware.SessionMiddleware',
28         'django.contrib.auth.middleware.AuthenticationMiddleware',
29         'django.middleware.doc.XViewMiddleware',
30     )
32 Django applies middleware in the order it's defined in ``MIDDLEWARE_CLASSES``,
33 except in the case of response and exception middleware, which is applied in
34 reverse order.
36 A Django installation doesn't require any middleware -- e.g.,
37 ``MIDDLEWARE_CLASSES`` can be empty, if you'd like -- but it's strongly
38 suggested that you use ``CommonMiddleware``.
40 Available middleware
41 ====================
43 django.middleware.cache.CacheMiddleware
44 ---------------------------------------
46 Enables site-wide cache. If this is enabled, each Django-powered page will be
47 cached for as long as the ``CACHE_MIDDLEWARE_SECONDS`` setting defines. See
48 the `cache documentation`_.
50 .. _`cache documentation`: ../cache/#the-per-site-cache
52 django.middleware.common.CommonMiddleware
53 -----------------------------------------
55 Adds a few conveniences for perfectionists:
57 * Forbids access to user agents in the ``DISALLOWED_USER_AGENTS`` setting,
58   which should be a list of strings.
60 * Performs URL rewriting based on the ``APPEND_SLASH`` and ``PREPEND_WWW``
61   settings.
63   If ``APPEND_SLASH`` is ``True`` and the initial URL doesn't end with a slash,
64   and it is not found in the URLconf, then a new URL is formed by appending a
65   slash at the end. If this new URL is found in the URLconf, then Django
66   redirects the request to this new URL. Otherwise, the initial URL is
67   processed as usual.
69   For example, ``foo.com/bar`` will be redirected to ``foo.com/bar/`` if you
70   don't have a valid URL pattern for ``foo.com/bar`` but *do* have a valid
71   pattern for ``foo.com/bar/``.
73   **New in Django development version:** The behavior of ``APPEND_SLASH`` has
74   changed slightly in the development version. It didn't used to check whether
75   the pattern was matched in the URLconf.
77   If ``PREPEND_WWW`` is ``True``, URLs that lack a leading "www." will be
78   redirected to the same URL with a leading "www."
80   Both of these options are meant to normalize URLs. The philosophy is that
81   each URL should exist in one, and only one, place. Technically a URL
82   ``foo.com/bar`` is distinct from ``foo.com/bar/`` -- a search-engine
83   indexer would treat them as separate URLs -- so it's best practice to
84   normalize URLs.
86 * Handles ETags based on the ``USE_ETAGS`` setting. If ``USE_ETAGS`` is set
87   to ``True``, Django will calculate an ETag for each request by
88   MD5-hashing the page content, and it'll take care of sending
89   ``Not Modified`` responses, if appropriate.
91 django.middleware.doc.XViewMiddleware
92 -------------------------------------
94 Sends custom ``X-View`` HTTP headers to HEAD requests that come from IP
95 addresses defined in the ``INTERNAL_IPS`` setting. This is used by Django's
96 automatic documentation system.
98 django.middleware.gzip.GZipMiddleware
99 -------------------------------------
101 Compresses content for browsers that understand gzip compression (all modern
102 browsers).
104 It is suggested to place this first in the middleware list, so that the
105 compression of the response content is the last thing that happens. Will not
106 compress content bodies less than 200 bytes long, when the response code is
107 something other than 200, JavaScript files (for IE compatibitility), or
108 responses that have the ``Content-Encoding`` header already specified.
110 django.middleware.http.ConditionalGetMiddleware
111 -----------------------------------------------
113 Handles conditional GET operations. If the response has a ``ETag`` or
114 ``Last-Modified`` header, and the request has ``If-None-Match`` or
115 ``If-Modified-Since``, the response is replaced by an HttpNotModified.
117 Also sets the ``Date`` and ``Content-Length`` response-headers.
119 django.middleware.http.SetRemoteAddrFromForwardedFor
120 ----------------------------------------------------
122 Sets ``request.META['REMOTE_ADDR']`` based on
123 ``request.META['HTTP_X_FORWARDED_FOR']``, if the latter is set. This is useful
124 if you're sitting behind a reverse proxy that causes each request's
125 ``REMOTE_ADDR`` to be set to ``127.0.0.1``.
127 **Important note:** This does NOT validate ``HTTP_X_FORWARDED_FOR``. If you're
128 not behind a reverse proxy that sets ``HTTP_X_FORWARDED_FOR`` automatically, do
129 not use this middleware. Anybody can spoof the value of
130 ``HTTP_X_FORWARDED_FOR``, and because this sets ``REMOTE_ADDR`` based on
131 ``HTTP_X_FORWARDED_FOR``, that means anybody can "fake" their IP address. Only
132 use this when you can absolutely trust the value of ``HTTP_X_FORWARDED_FOR``.
134 django.middleware.locale.LocaleMiddleware
135 -----------------------------------------
137 Enables language selection based on data from the request. It customizes content
138 for each user. See the `internationalization documentation`_.
140 .. _`internationalization documentation`: ../i18n/
142 django.contrib.sessions.middleware.SessionMiddleware
143 ----------------------------------------------------
145 Enables session support. See the `session documentation`_.
147 .. _`session documentation`: ../sessions/
149 django.contrib.auth.middleware.AuthenticationMiddleware
150 -------------------------------------------------------
152 Adds the ``user`` attribute, representing the currently-logged-in user, to
153 every incoming ``HttpRequest`` object. See `Authentication in Web requests`_.
155 .. _Authentication in Web requests: ../authentication/#authentication-in-web-requests
157 django.contrib.csrf.middleware.CsrfMiddleware
158 ---------------------------------------------
160 **New in Django development version**
162 Adds protection against Cross Site Request Forgeries by adding hidden form
163 fields to POST forms and checking requests for the correct value. See the
164 `Cross Site Request Forgery protection documentation`_.
166 .. _`Cross Site Request Forgery protection documentation`: ../csrf/
168 django.middleware.transaction.TransactionMiddleware
169 ---------------------------------------------------
171 Binds commit and rollback to the request/response phase. If a view function runs
172 successfully, a commit is done. If it fails with an exception, a rollback is
173 done.
175 The order of this middleware in the stack is important: middleware modules
176 running outside of it run with commit-on-save - the default Django behavior.
177 Middleware modules running inside it (coming later in the stack) will be under
178 the same transaction control as the view functions.
180 See the `transaction management documentation`_.
182 .. _`transaction management documentation`: ../transactions/
184 Writing your own middleware
185 ===========================
187 Writing your own middleware is easy. Each middleware component is a single
188 Python class that defines one or more of the following methods:
190 ``process_request``
191 -------------------
193 Interface: ``process_request(self, request)``
195 ``request`` is an ``HttpRequest`` object. This method is called on each
196 request, before Django decides which view to execute.
198 ``process_request()`` should return either ``None`` or an ``HttpResponse``
199 object. If it returns ``None``, Django will continue processing this request,
200 executing any other middleware and, then, the appropriate view. If it returns
201 an ``HttpResponse`` object, Django won't bother calling ANY other request,
202 view or exception middleware, or the appropriate view; it'll return that
203 ``HttpResponse``. Response middleware is always called on every response.
205 ``process_view``
206 ----------------
208 Interface: ``process_view(self, request, view_func, view_args, view_kwargs)``
210 ``request`` is an ``HttpRequest`` object. ``view_func`` is the Python function
211 that Django is about to use. (It's the actual function object, not the name of
212 the function as a string.) ``view_args`` is a list of positional arguments that
213 will be passed to the view, and ``view_kwargs`` is a dictionary of keyword
214 arguments that will be passed to the view. Neither ``view_args`` nor
215 ``view_kwargs`` include the first view argument (``request``).
217 ``process_view()`` is called just before Django calls the view. It should
218 return either ``None`` or an ``HttpResponse`` object. If it returns ``None``,
219 Django will continue processing this request, executing any other
220 ``process_view()`` middleware and, then, the appropriate view. If it returns an
221 ``HttpResponse`` object, Django won't bother calling ANY other request, view
222 or exception middleware, or the appropriate view; it'll return that
223 ``HttpResponse``. Response middleware is always called on every response.
225 ``process_response``
226 --------------------
228 Interface: ``process_response(self, request, response)``
230 ``request`` is an ``HttpRequest`` object. ``response`` is the ``HttpResponse``
231 object returned by a Django view.
233 ``process_response()`` should return an ``HttpResponse`` object. It could alter
234 the given ``response``, or it could create and return a brand-new
235 ``HttpResponse``.
237 ``process_exception``
238 ---------------------
240 Interface: ``process_exception(self, request, exception)``
242 ``request`` is an ``HttpRequest`` object. ``exception`` is an ``Exception``
243 object raised by the view function.
245 Django calls ``process_exception()`` when a view raises an exception.
246 ``process_exception()`` should return either ``None`` or an ``HttpResponse``
247 object. If it returns an ``HttpResponse`` object, the response will be returned
248 to the browser. Otherwise, default exception handling kicks in.
250 ``__init__``
251 ------------
253 Most middleware classes won't need an initializer since middleware classes are
254 essentially placeholders for the ``process_*`` methods. If you do need some
255 global state you may use ``__init__`` to set up. However, keep in mind a couple
256 of caveats:
258     * Django initializes your middleware without any arguments, so you can't
259       define ``__init__`` as requiring any arguments.
260       
261     * Unlike the ``process_*`` methods which get called once per request,
262       ``__init__`` gets called only *once*, when the web server starts up.
264 Marking middleware as unused
265 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
267 It's sometimes useful to determine at run-time whether a piece of middleware
268 should be used. In these cases, your middleware's ``__init__`` method may raise
269 ``django.core.exceptions.MiddlewareNotUsed``. Django will then remove that piece
270 of middleware from the middleware process.
272 Guidelines
273 ----------
275     * Middleware classes don't have to subclass anything.
277     * The middleware class can live anywhere on your Python path. All Django
278       cares about is that the ``MIDDLEWARE_CLASSES`` setting includes the path
279       to it.
281     * Feel free to look at Django's available middleware for examples. The
282       core Django middleware classes are in ``django/middleware/`` in the
283       Django distribution. The session middleware is in
284       ``django/contrib/sessions``.
286     * If you write a middleware component that you think would be useful to
287       other people, contribute to the community! Let us know, and we'll
288       consider adding it to Django.