PageRenderTime 61ms CodeModel.GetById 21ms app.highlight 2ms RepoModel.GetById 18ms app.codeStats 0ms

/docs/topics/http/middleware.txt

https://code.google.com/p/mango-py/
Plain Text | 213 lines | 159 code | 54 blank | 0 comment | 0 complexity | 8bbb8caa59f9175f56fc3c15f51dcc1d MD5 | raw file
  1==========
  2Middleware
  3==========
  4
  5Middleware is a framework of hooks into Django's request/response processing.
  6It's a light, low-level "plugin" system for globally altering Django's input
  7and/or output.
  8
  9Each middleware component is responsible for doing some specific function. For
 10example, Django includes a middleware component, ``XViewMiddleware``, that adds
 11an ``"X-View"`` HTTP header to every response to a ``HEAD`` request.
 12
 13This document explains how middleware works, how you activate middleware, and
 14how to write your own middleware. Django ships with some built-in middleware
 15you can use right out of the box; they're documented in the :doc:`built-in
 16middleware reference </ref/middleware>`.
 17
 18Activating middleware
 19=====================
 20
 21To activate a middleware component, add it to the :setting:`MIDDLEWARE_CLASSES`
 22list in your Django settings. In :setting:`MIDDLEWARE_CLASSES`, each middleware
 23component is represented by a string: the full Python path to the middleware's
 24class name. For example, here's the default :setting:`MIDDLEWARE_CLASSES`
 25created 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
 35During the request phases (:meth:`process_request` and :meth:`process_view`
 36middleware), 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
 39classes are applied in reverse order, from the bottom up. You can think of it
 40like 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
 47A Django installation doesn't require any middleware -- e.g.,
 48:setting:`MIDDLEWARE_CLASSES` can be empty, if you'd like -- but it's strongly
 49suggested that you at least use
 50:class:`~django.middleware.common.CommonMiddleware`.
 51
 52Writing your own middleware
 53===========================
 54
 55Writing your own middleware is easy. Each middleware component is a single
 56Python 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
 66called 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
 70continue processing this request, executing any other middleware and, then, the
 71appropriate view. If it returns an :class:`~django.http.HttpResponse` object,
 72Django won't bother calling ANY other request, view or exception middleware, or
 73the appropriate view; it'll return that :class:`~django.http.HttpResponse`.
 74Response 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
 84the Python function that Django is about to use. (It's the actual function
 85object, not the name of the function as a string.) ``view_args`` is a list of
 86positional arguments that will be passed to the view, and ``view_kwargs`` is a
 87dictionary 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
 92return either ``None`` or an :class:`~django.http.HttpResponse` object. If it
 93returns ``None``, Django will continue processing this request, executing any
 94other ``process_view()`` middleware and, then, the appropriate view. If it
 95returns an :class:`~django.http.HttpResponse` object, Django won't bother
 96calling ANY other request, view or exception middleware, or the appropriate
 97view; it'll return that :class:`~django.http.HttpResponse`. Response
 98middleware is always called on every response.
 99
100.. _template-response-middleware:
101
102``process_template_response``
103-----------------------------
104
105.. versionadded:: 1.3
106
107.. method:: process_template_response(self, request, response)
108
109``request`` is an :class:`~django.http.HttpRequest` object. ``response`` is the
110:class:`~django.template.response.SimpleTemplateResponse` subclass (e.g.
111:class:`~django.template.response.TemplateResponse`) object returned by a
112Django view.
113
114``process_template_response()`` must return an
115:class:`~django.template.response.SimpleTemplateResponse` (or its subclass)
116object. It could alter the given ``response`` by changing
117``response.template_name`` and ``response.context_data``, or it could
118create and return a brand-new
119:class:`~django.template.response.SimpleTemplateResponse` (or its subclass)
120instance.
121
122``process_template_response()`` will only be called if the response
123instance has a ``render()`` method, indicating that it is a
124:class:`~django.template.response.TemplateResponse`.
125
126You don't need to explicitly render responses -- responses will be
127automatically rendered once all template response middleware has been
128called.
129
130Middleware are run in reverse order during the response phase, which
131includes process_template_response.
132
133.. _response-middleware:
134
135``process_response``
136--------------------
137
138.. method:: process_response(self, request, response)
139
140``request`` is an :class:`~django.http.HttpRequest` object. ``response`` is the
141:class:`~django.http.HttpResponse` object returned by a Django view.
142
143``process_response()`` must return an :class:`~django.http.HttpResponse`
144object. It could alter the given ``response``, or it could create and return a
145brand-new :class:`~django.http.HttpResponse`.
146
147Unlike the ``process_request()`` and ``process_view()`` methods, the
148``process_response()`` method is always called, even if the ``process_request()``
149and ``process_view()`` methods of the same middleware class were skipped because
150an earlier middleware method returned an :class:`~django.http.HttpResponse`
151(this means that your ``process_response()`` method cannot rely on setup done in
152``process_request()``, for example). In addition, during the response phase the
153classes are applied in reverse order, from the bottom up. This means classes
154defined at the end of :setting:`MIDDLEWARE_CLASSES` will be run first.
155
156
157.. _exception-middleware:
158
159``process_exception``
160---------------------
161
162.. method:: process_exception(self, request, exception)
163
164``request`` is an :class:`~django.http.HttpRequest` object. ``exception`` is an
165``Exception`` object raised by the view function.
166
167Django calls ``process_exception()`` when a view raises an exception.
168``process_exception()`` should return either ``None`` or an
169:class:`~django.http.HttpResponse` object. If it returns an
170:class:`~django.http.HttpResponse` object, the response will be returned to
171the browser. Otherwise, default exception handling kicks in.
172
173Again, middleware are run in reverse order during the response phase, which
174includes ``process_exception``. If an exception middleware returns a response,
175the middleware classes above that middleware will not be called at all.
176
177``__init__``
178------------
179
180Most middleware classes won't need an initializer since middleware classes are
181essentially placeholders for the ``process_*`` methods. If you do need some
182global state you may use ``__init__`` to set up. However, keep in mind a couple
183of caveats:
184
185    * Django initializes your middleware without any arguments, so you can't
186      define ``__init__`` as requiring any arguments.
187
188    * Unlike the ``process_*`` methods which get called once per request,
189      ``__init__`` gets called only *once*, when the Web server starts up.
190
191Marking middleware as unused
192~~~~~~~~~~~~~~~~~~~~~~~~~~~~
193
194It's sometimes useful to determine at run-time whether a piece of middleware
195should be used. In these cases, your middleware's ``__init__`` method may raise
196``django.core.exceptions.MiddlewareNotUsed``. Django will then remove that
197piece of middleware from the middleware process.
198
199Guidelines
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 :setting:`MIDDLEWARE_CLASSES` setting includes
206      the path to it.
207
208    * Feel free to look at :doc:`Django's available middleware
209      </ref/middleware>` for examples.
210
211    * If you write a middleware component that you think would be useful to
212      other people, contribute to the community! :doc:`Let us know
213      </internals/contributing>`, and we'll consider adding it to Django.