Django

Code

root/django/branches/new-admin/docs/middleware.txt

Revision 1169, 7.0 kB (checked in by rjwittams, 3 years ago)

Merged to trunk r1168

Line 
1 ==========
2 Middleware
3 ==========
4
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.
8
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.
12
13 This document explains all middleware components that come with Django, how to
14 use them, and how to write your own middleware.
15
16 Activating middleware
17 =====================
18
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``::
24
25     MIDDLEWARE_CLASSES = (
26         "django.middleware.common.CommonMiddleware",
27         "django.middleware.doc.XViewMiddleware",
28     )
29
30 Django applies middleware in the order it's defined in ``MIDDLEWARE_CLASSES``,
31 except in the case of response and exception middleware, which is applied in
32 reverse order.
33
34 A Django installation doesn't require any middleware -- e.g.,
35 ``MIDDLEWARE_CLASSES`` can be empty, if you'd like -- but it's strongly
36 suggested that you use ``CommonMiddleware``.
37
38 Available middleware
39 ====================
40
41 django.middleware.cache.CacheMiddleware
42 ---------------------------------------
43
44 Enables site-wide cache. If this is enabled, each Django-powered page will be
45 cached for as long as the ``CACHE_MIDDLEWARE_SECONDS`` setting defines. See
46 the `cache documentation`_.
47
48 .. _`cache documentation`: http://www.djangoproject.com/documentation/cache/#the-per-site-cache
49
50 django.middleware.common.CommonMiddleware
51 -----------------------------------------
52
53 Adds a few conveniences for perfectionists:
54
55 * Forbids access to user agents in the ``DISALLOWED_USER_AGENTS`` setting,
56   which should be a list of strings.
57
58 * Performs URL rewriting based on the ``APPEND_SLASH`` and ``PREPEND_WWW``
59   settings. If ``APPEND_SLASH`` is ``True``, URLs that lack a trailing
60   slash will be redirected to the same URL with a trailing slash. If
61   ``PREPEND_WWW`` is ``True``, URLs that lack a leading "www." will be
62   redirected to the same URL with a leading "www."
63
64   Both of these options are meant to normalize URLs. The philosophy is that
65   each URL should exist in one, and only one, place. Technically a URL
66   ``foo.com/bar`` is distinct from ``foo.com/bar/`` -- a search-engine
67   indexer would treat them as separate URLs -- so it's best practice to
68   normalize URLs.
69
70 * Handles ETags based on the ``USE_ETAGS`` setting. If ``USE_ETAGS`` is set
71   to ``True``, Django will calculate an ETag for each request by
72   MD5-hashing the page content, and it'll take care of sending
73   ``Not Modified`` responses, if appropriate.
74
75 django.middleware.doc.XViewMiddleware
76 -------------------------------------
77
78 Sends custom ``X-View`` HTTP headers to HEAD requests that come from IP
79 addresses defined in the ``INTERNAL_IPS`` setting. This is used by Django's
80 automatic documentation system.
81
82 django.middleware.gzip.GZipMiddleware
83 -------------------------------------
84
85 Compresses content for browsers that understand gzip compression (all modern
86 browsers).
87
88 django.middleware.http.ConditionalGetMiddleware
89 -----------------------------------------------
90
91 Handles conditional GET operations. If the response has a ``ETag`` or
92 ``Last-Modified`` header, and the request has ``If-None-Match`` or
93 ``If-Modified-Since``, the response is replaced by an HttpNotModified.
94
95 Also removes the content from any response to a HEAD request and sets the
96 ``Date`` and ``Content-Length`` response-headers.
97
98 django.middleware.sessions.SessionMiddleware
99 --------------------------------------------
100
101 Enables session support. See the `session documentation`_.
102
103 .. _`session documentation`: http://www.djangoproject.com/documentation/sessions/
104
105 Writing your own middleware
106 ===========================
107
108 Writing your own middleware is easy. Each middleware component is a single
109 Python class that defines one or more of the following methods:
110
111 process_request
112 ---------------
113
114 Interface: ``process_request(self, request)``
115
116 ``request`` is an ``HttpRequest`` object. This method is called on each
117 request, before Django decides which view to execute.
118
119 ``process_request()`` should return either ``None`` or an ``HttpResponse``
120 object. If it returns ``None``, Django will continue processing this request,
121 executing any other middleware and, then, the appropriate view. If it returns
122 an ``HttpResponse`` object, Django won't bother calling ANY other middleware or
123 the appropriate view; it'll return that ``HttpResponse``.
124
125 process_view
126 ------------
127
128 Interface: ``process_view(self, request, view_func, param_dict)``
129
130 ``request`` is an ``HttpRequest`` object. ``view_func`` is the Python function
131 that Django is about to use. (It's the actual function object, not the name of
132 the function as a string.) ``param_dict`` is a dictionary of keyword arguments
133 that will be passed to the view -- NOT including the first argument (``request``).
134
135 ``process_view()`` is called just before Django calls the view. It should
136 return either ``None`` or an ``HttpResponse`` object. If it returns ``None``,
137 Django will continue processing this request, executing any other
138 ``process_view()`` middleware and, then, the appropriate view. If it returns an
139 ``HttpResponse`` object, Django won't bother calling ANY other middleware or
140 the appropriate view; it'll return that ``HttpResponse``.
141
142 process_response
143 ----------------
144
145 Interface: ``process_response(self, request, response)``
146
147 ``request`` is an ``HttpRequest`` object. ``response`` is the ``HttpResponse``
148 object returned by a Django view.
149
150 ``process_response()`` should return an ``HttpResponse`` object. It could alter
151 the given ``response``, or it could create and return a brand-new
152 ``HttpResponse``.
153
154 process_exception
155 -----------------
156
157 Interface: ``process_exception(self, request, exception)``
158
159 ``request`` is an ``HttpRequest`` object. ``exception`` is an ``Exception``
160 object raised by the view function.
161
162 Django calls ``process_exception()`` when a view raises an exception.
163 ``process_exception()`` should return either ``None`` or an ``HttpResponse``
164 object. If it returns an ``HttpResponse`` object, the response will be returned
165 to the browser. Otherwise, default exception handling kicks in.
166
167 Guidelines
168 ----------
169
170     * Middleware classes don't have to subclass anything.
171
172     * The middleware class can live anywhere on your Python path. All Django
173       cares about is that the ``MIDDLEWARE_CLASSES`` setting includes the path
174       to it.
175
176     * Feel free to look at Django's available middleware for examples. The
177       default Django middleware classes are in ``django/middleware/`` in the
178       Django distribution.
179
180     * If you write a middleware component that you think would be useful to
181       other people, contribute to the community! Let us know, and we'll
182       consider adding it to Django.
Note: See TracBrowser for help on using the browser.