Django

Code

root/django/tags/releases/0.95/docs/middleware.txt

Revision 2980, 8.6 kB (checked in by adrian, 2 years ago)

Fixed #1998 -- Changed double quotes to single quotes

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.contrib.sessions.middleware.SessionMiddleware',
28         'django.contrib.auth.middleware.AuthenticationMiddleware',
29         'django.middleware.doc.XViewMiddleware',
30     )
31
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.
35
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``.
39
40 Available middleware
41 ====================
42
43 django.middleware.cache.CacheMiddleware
44 ---------------------------------------
45
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`_.
49
50 .. _`cache documentation`: http://www.djangoproject.com/documentation/cache/#the-per-site-cache
51
52 django.middleware.common.CommonMiddleware
53 -----------------------------------------
54
55 Adds a few conveniences for perfectionists:
56
57 * Forbids access to user agents in the ``DISALLOWED_USER_AGENTS`` setting,
58   which should be a list of strings.
59
60 * Performs URL rewriting based on the ``APPEND_SLASH`` and ``PREPEND_WWW``
61   settings. If ``APPEND_SLASH`` is ``True``, URLs that lack a trailing
62   slash will be redirected to the same URL with a trailing slash, unless the
63   last component in the path contains a period. So ``foo.com/bar`` is
64   redirected to ``foo.com/bar/``, but ``foo.com/bar/file.txt`` is passed
65   through unchanged.
66  
67   If ``PREPEND_WWW`` is ``True``, URLs that lack a leading "www." will be
68   redirected to the same URL with a leading "www."
69
70   Both of these options are meant to normalize URLs. The philosophy is that
71   each URL should exist in one, and only one, place. Technically a URL
72   ``foo.com/bar`` is distinct from ``foo.com/bar/`` -- a search-engine
73   indexer would treat them as separate URLs -- so it's best practice to
74   normalize URLs.
75
76 * Handles ETags based on the ``USE_ETAGS`` setting. If ``USE_ETAGS`` is set
77   to ``True``, Django will calculate an ETag for each request by
78   MD5-hashing the page content, and it'll take care of sending
79   ``Not Modified`` responses, if appropriate.
80
81 django.middleware.doc.XViewMiddleware
82 -------------------------------------
83
84 Sends custom ``X-View`` HTTP headers to HEAD requests that come from IP
85 addresses defined in the ``INTERNAL_IPS`` setting. This is used by Django's
86 automatic documentation system.
87
88 django.middleware.gzip.GZipMiddleware
89 -------------------------------------
90
91 Compresses content for browsers that understand gzip compression (all modern
92 browsers).
93
94 django.middleware.http.ConditionalGetMiddleware
95 -----------------------------------------------
96
97 Handles conditional GET operations. If the response has a ``ETag`` or
98 ``Last-Modified`` header, and the request has ``If-None-Match`` or
99 ``If-Modified-Since``, the response is replaced by an HttpNotModified.
100
101 Also removes the content from any response to a HEAD request and sets the
102 ``Date`` and ``Content-Length`` response-headers.
103
104 django.contrib.sessions.middleware.SessionMiddleware
105 ----------------------------------------------------
106
107 Enables session support. See the `session documentation`_.
108
109 .. _`session documentation`: http://www.djangoproject.com/documentation/sessions/
110
111 django.contrib.auth.middleware.AuthenticationMiddleware
112 -------------------------------------------------------
113
114 Adds the ``user`` attribute, representing the currently-logged-in user, to
115 every incoming ``HttpRequest`` object. See `Authentication in Web requests`_.
116
117 .. _Authentication in Web requests: http://www.djangoproject.com/documentation/authentication/#authentication-in-web-requests
118
119 django.middleware.transaction.TransactionMiddleware
120 ---------------------------------------------------
121
122 Binds commit and rollback to the request/response phase. If a view function runs
123 successfully, a commit is done. If it fails with an exception, a rollback is
124 done.
125
126 The order of this middleware in the stack is important: middleware modules
127 running outside of it run with commit-on-save - the default Django behavior.
128 Middleware modules running inside it (coming later in the stack) will be under
129 the same transaction control as the view functions.
130
131 See the `transaction management documentation`_.
132
133 .. _`transaction management documentation`: http://www.djangoproject.com/documentation/transactions/
134
135 Writing your own middleware
136 ===========================
137
138 Writing your own middleware is easy. Each middleware component is a single
139 Python class that defines one or more of the following methods:
140
141 process_request
142 ---------------
143
144 Interface: ``process_request(self, request)``
145
146 ``request`` is an ``HttpRequest`` object. This method is called on each
147 request, before Django decides which view to execute.
148
149 ``process_request()`` should return either ``None`` or an ``HttpResponse``
150 object. If it returns ``None``, Django will continue processing this request,
151 executing any other middleware and, then, the appropriate view. If it returns
152 an ``HttpResponse`` object, Django won't bother calling ANY other middleware or
153 the appropriate view; it'll return that ``HttpResponse``.
154
155 process_view
156 ------------
157
158 Interface: ``process_view(self, request, view_func, view_args, view_kwargs)``
159
160 ``request`` is an ``HttpRequest`` object. ``view_func`` is the Python function
161 that Django is about to use. (It's the actual function object, not the name of
162 the function as a string.) ``view_args`` is a list of positional arguments that
163 will be passed to the view, and ``view_kwargs`` is a dictionary of keyword
164 arguments that will be passed to the view. Neither ``view_args`` nor
165 ``view_kwargs`` include the first view argument (``request``).
166
167 ``process_view()`` is called just before Django calls the view. It should
168 return either ``None`` or an ``HttpResponse`` object. If it returns ``None``,
169 Django will continue processing this request, executing any other
170 ``process_view()`` middleware and, then, the appropriate view. If it returns an
171 ``HttpResponse`` object, Django won't bother calling ANY other middleware or
172 the appropriate view; it'll return that ``HttpResponse``.
173
174 process_response
175 ----------------
176
177 Interface: ``process_response(self, request, response)``
178
179 ``request`` is an ``HttpRequest`` object. ``response`` is the ``HttpResponse``
180 object returned by a Django view.
181
182 ``process_response()`` should return an ``HttpResponse`` object. It could alter
183 the given ``response``, or it could create and return a brand-new
184 ``HttpResponse``.
185
186 process_exception
187 -----------------
188
189 Interface: ``process_exception(self, request, exception)``
190
191 ``request`` is an ``HttpRequest`` object. ``exception`` is an ``Exception``
192 object raised by the view function.
193
194 Django calls ``process_exception()`` when a view raises an exception.
195 ``process_exception()`` should return either ``None`` or an ``HttpResponse``
196 object. If it returns an ``HttpResponse`` object, the response will be returned
197 to the browser. Otherwise, default exception handling kicks in.
198
199 Guidelines
200 ----------
201
202     * Middleware classes don't have to subclass anything.
203
204     * The middleware class can live anywhere on your Python path. All Django
205       cares about is that the ``MIDDLEWARE_CLASSES`` setting includes the path
206       to it.
207
208     * Feel free to look at Django's available middleware for examples. The
209       core Django middleware classes are in ``django/middleware/`` in the
210       Django distribution. The session middleware is in ``django/contrib/sessions``.
211
212     * If you write a middleware component that you think would be useful to
213       other people, contribute to the community! Let us know, and we'll
214       consider adding it to Django.
Note: See TracBrowser for help on using the browser.