conditional-view-processing.txt 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210
  1. .. _topics-conditional-processing:
  2. ===========================
  3. Conditional View Processing
  4. ===========================
  5. .. versionadded:: 1.1
  6. HTTP clients can send a number of headers to tell the server about copies of a
  7. resource that they have already seen. This is commonly used when retrieving a
  8. web page (using an HTTP ``GET`` request) to avoid sending all the data for
  9. something the client has already retrieved. However, the same headers can be
  10. used for all HTTP methods (``POST``, ``PUT``, ``DELETE``, etc).
  11. For each page (response) that Django sends back from a view, it might provide
  12. two HTTP headers: the ``ETag`` header and the ``Last-Modified`` header. These
  13. headers are optional on HTTP responses. They can be set by your view function,
  14. or you can rely on the :class:`~django.middleware.common.CommonMiddleware`
  15. middleware to set the ``ETag`` header.
  16. When the client next requests the same resource, it might send along a header
  17. such as `If-modified-since`_, containing the date of the last modification
  18. time it was sent, or `If-none-match`_, containing the ``ETag`` it was sent.
  19. If there is no match with the ETag, or if the resource has not been modified,
  20. a 304 status code can be sent back, instead of a full response, telling the
  21. client that nothing has changed.
  22. .. _If-none-match: http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.26
  23. .. _If-modified-since: http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.25
  24. When you need more fine-grained control you may use per-view conditional
  25. processing functions.
  26. .. conditional-decorators:
  27. The ``condition`` decorator
  28. ===========================
  29. Sometimes (in fact, quite often) you can create functions to rapidly compute the ETag_
  30. value or the last-modified time for a resource, **without** needing to do all
  31. the computations needed to construct the full view. Django can then use these
  32. functions to provide an "early bailout" option for the view processing.
  33. Telling the client that the content has not been modified since the last
  34. request, perhaps.
  35. .. _ETag: http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.11
  36. These two functions are passed as parameters the
  37. ``django.views.decorators.http.condition`` decorator. This decorator uses
  38. the two functions (you only need to supply one, if you can't compute both
  39. quantities easily and quickly) to work out if the headers in the HTTP request
  40. match those on the resource. If they don't match, a new copy of the resource
  41. must be computed and your normal view is called.
  42. The ``condition`` decorator's signature looks like this::
  43. condition(etag_func=None, last_modified_func=None)
  44. The two functions, to compute the ETag and the last modified time, will be
  45. passed the incoming ``request`` object and the same parameters, in the same
  46. order, as the view function they are helping to wrap. The function passed
  47. ``last_modified`` should return a standard datetime value specifying the last
  48. time the resource was modified, or ``None`` if the resource doesn't exist. The
  49. function passed to the ``etag`` decorator should return a string representing
  50. the `Etag`_ for the resource, or ``None`` if it doesn't exist.
  51. Using this feature usefully is probably best explained with an example.
  52. Suppose you have this pair of models, representing a simple blog system::
  53. import datetime
  54. from django.db import models
  55. class Blog(models.Model):
  56. ...
  57. class Entry(models.Model):
  58. blog = models.ForeignKey(Blog)
  59. published = models.DateTimeField(default=datetime.datetime.now)
  60. ...
  61. If the front page, displaying the latest blog entries, only changes when you
  62. add a new blog entry, you can compute the last modified time very quickly. You
  63. need the latest ``published`` date for every entry associated with that blog.
  64. One way to do this would be::
  65. from django.db.models import Max
  66. def latest_entry(request, blog_id):
  67. return Entry.objects.filter(blog=blog_id).aggregate(Max("published"))
  68. You can then use this function to provide early detection of an unchanged page
  69. for your front page view::
  70. from django.views.decorators.http import condition
  71. @condition(last_modified_func=latest_entry)
  72. def front_page(request, blog_id):
  73. ...
  74. Of course, if you're using Python 2.3 or prefer not to use the decorator
  75. syntax, you can write the same code as follows, there is no difference::
  76. def front_page(request, blog_id):
  77. ...
  78. front_page = condition(last_modified_func=latest_entry)(front_page)
  79. Shortcuts for only computing one value
  80. ======================================
  81. As a general rule, if you can provide functions to compute *both* the ETag and
  82. the last modified time, you should do so. You don't know which headers any
  83. given HTTP client will send you, so be prepared to handle both. However,
  84. sometimes only one value is easy to compute and Django provides decorators
  85. that handle only ETag or only last-modified computations.
  86. The ``django.views.decorators.http.etag`` and
  87. ``django.views.decorators.http.last_modified`` decorators are passed the same
  88. type of functions as the ``condition`` decorator. Their signatures are::
  89. etag(etag_func)
  90. last_modified(last_modified_func)
  91. We could write the earlier example, which only uses a last-modified function,
  92. using one of these decorators::
  93. @last_modified(latest_entry)
  94. def front_page(request, blog_id):
  95. ...
  96. ...or::
  97. def front_page(request, blog_id):
  98. ...
  99. front_page = last_modified(latest_entry)(front_page)
  100. Use ``condition`` when testing both conditions
  101. ------------------------------------------------
  102. It might look nicer to some people to try and chain the ``etag`` and
  103. ``last_modified`` decorators if you want to test both preconditions. However,
  104. this would lead to incorrect behavior.
  105. ::
  106. # Bad code. Don't do this!
  107. @etag(etag_func)
  108. @last_modified(last_modified_func)
  109. def my_view(request):
  110. # ...
  111. # End of bad code.
  112. The first decorator doesn't know anything about the second and might
  113. answer that the response is not modified even if the second decorators would
  114. determine otherwise. The ``condition`` decorator uses both callback functions
  115. simultaneously to work out the right action to take.
  116. Using the decorators with other HTTP methods
  117. ============================================
  118. The ``condition`` decorator is useful for more than only ``GET`` and
  119. ``HEAD`` requests (``HEAD`` requests are the same as ``GET`` in this
  120. situation). It can be used also to be used to provide checking for ``POST``,
  121. ``PUT`` and ``DELETE`` requests. In these situations, the idea isn't to return
  122. a "not modified" response, but to tell the client that the resource they are
  123. trying to change has been altered in the meantime.
  124. For example, consider the following exchange between the client and server:
  125. 1. Client requests ``/foo/``.
  126. 2. Server responds with some content with an ETag of ``"abcd1234"``.
  127. 3. Client sends an HTTP ``PUT`` request to ``/foo/`` to update the
  128. resource. It also sends an ``If-Match: "abcd1234"`` header to specify
  129. the version it is trying to update.
  130. 4. Server checks to see if the resource has changed, by computing the ETag
  131. the same way it does for a ``GET`` request (using the same function).
  132. If the resource *has* changed, it will return a 412 status code code,
  133. meaning "precondition failed".
  134. 5. Client sends a ``GET`` request to ``/foo/``, after receiving a 412
  135. response, to retrieve an updated version of the content before updating
  136. it.
  137. The important thing this example shows is that the same functions can be used
  138. to compute the ETag and last modification values in all situations. In fact,
  139. you **should** use the same functions, so that the same values are returned
  140. every time.
  141. Comparison with middleware conditional processing
  142. =================================================
  143. You may notice that Django already provides simple and straightforward
  144. conditional ``GET`` handling via the
  145. :class:`django.middleware.http.ConditionalGetMiddleware` and
  146. :class:`~django.middleware.common.CommonMiddleware`. Whilst certainly being
  147. easy to use and suitable for many situations, those pieces of middleware
  148. functionality have limitations for advanced usage:
  149. * They are applied globally to all views in your project
  150. * They don't save you from generating the response itself, which may be
  151. expensive
  152. * They are only appropriate for HTTP ``GET`` requests.
  153. You should choose the most appropriate tool for your particular problem here.
  154. If you have a way to compute ETags and modification times quickly and if some
  155. view takes a while to generate the content, you should consider using the
  156. ``condition`` decorator described in this document. If everything already runs
  157. fairly quickly, stick to using the middleware and the amount of network
  158. traffic sent back to the clients will still be reduced if the view hasn't
  159. changed.