|
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 how middleware works, how you activate middleware, and |
|
14 how to write your own middleware. Django ships with some built-in middleware |
|
15 you can use right out of the box; they're documented in the :doc:`built-in |
|
16 middleware reference </ref/middleware>`. |
|
17 |
|
18 Activating middleware |
|
19 ===================== |
|
20 |
|
21 To activate a middleware component, add it to the :setting:`MIDDLEWARE_CLASSES` |
|
22 list in your Django settings. In :setting:`MIDDLEWARE_CLASSES`, each middleware |
|
23 component is represented by a string: the full Python path to the middleware's |
|
24 class name. For example, here's the default :setting:`MIDDLEWARE_CLASSES` |
|
25 created by :djadmin:`django-admin.py startproject <startproject>`:: |
|
26 |
|
27 MIDDLEWARE_CLASSES = ( |
|
28 'django.middleware.common.CommonMiddleware', |
|
29 'django.contrib.sessions.middleware.SessionMiddleware', |
|
30 'django.middleware.csrf.CsrfViewMiddleware', |
|
31 'django.contrib.auth.middleware.AuthenticationMiddleware', |
|
32 'django.contrib.messages.middleware.MessageMiddleware', |
|
33 ) |
|
34 |
|
35 During the request phases (:meth:`process_request` and :meth:`process_view` |
|
36 middleware), Django applies middleware in the order it's defined in |
|
37 :setting:`MIDDLEWARE_CLASSES`, top-down. During the response phases |
|
38 (:meth:`process_response` and :meth:`process_exception` middleware), the |
|
39 classes are applied in reverse order, from the bottom up. You can think of it |
|
40 like an onion: each middleware class is a "layer" that wraps the view: |
|
41 |
|
42 .. image:: _images/middleware.png |
|
43 :width: 502 |
|
44 :height: 417 |
|
45 :alt: Middleware application order. |
|
46 |
|
47 A Django installation doesn't require any middleware -- e.g., |
|
48 :setting:`MIDDLEWARE_CLASSES` can be empty, if you'd like -- but it's strongly |
|
49 suggested that you at least use |
|
50 :class:`~django.middleware.common.CommonMiddleware`. |
|
51 |
|
52 Writing your own middleware |
|
53 =========================== |
|
54 |
|
55 Writing your own middleware is easy. Each middleware component is a single |
|
56 Python class that defines one or more of the following methods: |
|
57 |
|
58 .. _request-middleware: |
|
59 |
|
60 ``process_request`` |
|
61 ------------------- |
|
62 |
|
63 .. method:: process_request(self, request) |
|
64 |
|
65 ``request`` is an :class:`~django.http.HttpRequest` object. This method is |
|
66 called on each request, before Django decides which view to execute. |
|
67 |
|
68 ``process_request()`` should return either ``None`` or an |
|
69 :class:`~django.http.HttpResponse` object. If it returns ``None``, Django will |
|
70 continue processing this request, executing any other middleware and, then, the |
|
71 appropriate view. If it returns an :class:`~django.http.HttpResponse` object, |
|
72 Django won't bother calling ANY other request, view or exception middleware, or |
|
73 the appropriate view; it'll return that :class:`~django.http.HttpResponse`. |
|
74 Response middleware is always called on every response. |
|
75 |
|
76 .. _view-middleware: |
|
77 |
|
78 ``process_view`` |
|
79 ---------------- |
|
80 |
|
81 .. method:: process_view(self, request, view_func, view_args, view_kwargs) |
|
82 |
|
83 ``request`` is an :class:`~django.http.HttpRequest` object. ``view_func`` is |
|
84 the Python function that Django is about to use. (It's the actual function |
|
85 object, not the name of the function as a string.) ``view_args`` is a list of |
|
86 positional arguments that will be passed to the view, and ``view_kwargs`` is a |
|
87 dictionary of keyword arguments that will be passed to the view. Neither |
|
88 ``view_args`` nor ``view_kwargs`` include the first view argument |
|
89 (``request``). |
|
90 |
|
91 ``process_view()`` is called just before Django calls the view. It should |
|
92 return either ``None`` or an :class:`~django.http.HttpResponse` object. If it |
|
93 returns ``None``, Django will continue processing this request, executing any |
|
94 other ``process_view()`` middleware and, then, the appropriate view. If it |
|
95 returns an :class:`~django.http.HttpResponse` object, Django won't bother |
|
96 calling ANY other request, view or exception middleware, or the appropriate |
|
97 view; it'll return that :class:`~django.http.HttpResponse`. Response |
|
98 middleware is always called on every response. |
|
99 |
|
100 .. _response-middleware: |
|
101 |
|
102 ``process_response`` |
|
103 -------------------- |
|
104 |
|
105 .. method:: process_response(self, request, response) |
|
106 |
|
107 ``request`` is an :class:`~django.http.HttpRequest` object. ``response`` is the |
|
108 :class:`~django.http.HttpResponse` object returned by a Django view. |
|
109 |
|
110 ``process_response()`` must return an :class:`~django.http.HttpResponse` |
|
111 object. It could alter the given ``response``, or it could create and return a |
|
112 brand-new :class:`~django.http.HttpResponse`. |
|
113 |
|
114 Unlike the ``process_request()`` and ``process_view()`` methods, the |
|
115 ``process_response()`` method is always called, even if the ``process_request()`` |
|
116 and ``process_view()`` methods of the same middleware class were skipped because |
|
117 an earlier middleware method returned an :class:`~django.http.HttpResponse` |
|
118 (this means that your ``process_response()`` method cannot rely on setup done in |
|
119 ``process_request()``, for example). In addition, during the response phase the |
|
120 classes are applied in reverse order, from the bottom up. This means classes |
|
121 defined at the end of :setting:`MIDDLEWARE_CLASSES` will be run first. |
|
122 |
|
123 .. _exception-middleware: |
|
124 |
|
125 ``process_exception`` |
|
126 --------------------- |
|
127 |
|
128 .. method:: process_exception(self, request, exception) |
|
129 |
|
130 ``request`` is an :class:`~django.http.HttpRequest` object. ``exception`` is an |
|
131 ``Exception`` object raised by the view function. |
|
132 |
|
133 Django calls ``process_exception()`` when a view raises an exception. |
|
134 ``process_exception()`` should return either ``None`` or an |
|
135 :class:`~django.http.HttpResponse` object. If it returns an |
|
136 :class:`~django.http.HttpResponse` object, the response will be returned to |
|
137 the browser. Otherwise, default exception handling kicks in. |
|
138 |
|
139 Again, middleware are run in reverse order during the response phase, which |
|
140 includes ``process_exception``. If an exception middleware return a response, |
|
141 the middleware classes above that middleware will not be called at all. |
|
142 |
|
143 ``__init__`` |
|
144 ------------ |
|
145 |
|
146 Most middleware classes won't need an initializer since middleware classes are |
|
147 essentially placeholders for the ``process_*`` methods. If you do need some |
|
148 global state you may use ``__init__`` to set up. However, keep in mind a couple |
|
149 of caveats: |
|
150 |
|
151 * Django initializes your middleware without any arguments, so you can't |
|
152 define ``__init__`` as requiring any arguments. |
|
153 |
|
154 * Unlike the ``process_*`` methods which get called once per request, |
|
155 ``__init__`` gets called only *once*, when the Web server starts up. |
|
156 |
|
157 Marking middleware as unused |
|
158 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
|
159 |
|
160 It's sometimes useful to determine at run-time whether a piece of middleware |
|
161 should be used. In these cases, your middleware's ``__init__`` method may raise |
|
162 ``django.core.exceptions.MiddlewareNotUsed``. Django will then remove that |
|
163 piece of middleware from the middleware process. |
|
164 |
|
165 Guidelines |
|
166 ---------- |
|
167 |
|
168 * Middleware classes don't have to subclass anything. |
|
169 |
|
170 * The middleware class can live anywhere on your Python path. All Django |
|
171 cares about is that the :setting:`MIDDLEWARE_CLASSES` setting includes |
|
172 the path to it. |
|
173 |
|
174 * Feel free to look at :doc:`Django's available middleware |
|
175 </ref/middleware>` for examples. |
|
176 |
|
177 * If you write a middleware component that you think would be useful to |
|
178 other people, contribute to the community! :doc:`Let us know |
|
179 </internals/contributing>`, and we'll consider adding it to Django. |