conditional-view-processing.txt 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218
  1. ===========================
  2. Conditional View Processing
  3. ===========================
  4. HTTP clients can send a number of headers to tell the server about copies of a
  5. resource that they have already seen. This is commonly used when retrieving a
  6. web page (using an HTTP ``GET`` request) to avoid sending all the data for
  7. something the client has already retrieved. However, the same headers can be
  8. used for all HTTP methods (``POST``, ``PUT``, ``DELETE``, etc.).
  9. For each page (response) that Django sends back from a view, it might provide
  10. two HTTP headers: the ``ETag`` header and the ``Last-Modified`` header. These
  11. headers are optional on HTTP responses. They can be set by your view function,
  12. or you can rely on the :class:`~django.middleware.http.ConditionalGetMiddleware`
  13. middleware to set the ``ETag`` header.
  14. When the client next requests the same resource, it might send along a header
  15. such as either :rfc:`If-Modified-Since <9110#section-13.1.3>` or
  16. :rfc:`If-Unmodified-Since <9110#section-13.1.4>`, containing the date of the
  17. last modification time it was sent, or either :rfc:`If-Match
  18. <9110#section-13.1.1>` or :rfc:`If-None-Match <9110#section-13.1.2>`,
  19. containing the last ``ETag`` it was sent. If the current version of the page
  20. matches the ``ETag`` sent by the client, or if the resource has not been
  21. modified, a 304 status code can be sent back, instead of a full response,
  22. telling the client that nothing has changed. Depending on the header, if the
  23. page has been modified or does not match the ``ETag`` sent by the client, a 412
  24. status code (Precondition Failed) may be returned.
  25. When you need more fine-grained control you may use per-view conditional
  26. processing functions.
  27. .. _conditional-decorators:
  28. The ``condition`` decorator
  29. ===========================
  30. Sometimes (in fact, quite often) you can create functions to rapidly compute
  31. the :rfc:`ETag <9110#section-8.8.3>` value or the last-modified time for a
  32. resource, **without** needing to do all the computations needed to construct
  33. the full view. Django can then use these functions to provide an
  34. "early bailout" option for the view processing. Telling the client that the
  35. content has not been modified since the last request, perhaps.
  36. These two functions are passed as parameters to 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_func`` should return a standard datetime value specifying the
  48. last time the resource was modified, or ``None`` if the resource doesn't
  49. exist. The function passed to the ``etag`` decorator should return a string
  50. representing the :rfc:`ETag <9110#section-8.8.3>` for the resource, or ``None``
  51. if it doesn't exist.
  52. The decorator sets the ``ETag`` and ``Last-Modified`` headers on the response
  53. if they are not already set by the view and if the request's method is safe
  54. (``GET`` or ``HEAD``).
  55. Using this feature usefully is probably best explained with an example.
  56. Suppose you have this pair of models, representing a small blog system::
  57. import datetime
  58. from django.db import models
  59. class Blog(models.Model): ...
  60. class Entry(models.Model):
  61. blog = models.ForeignKey(Blog, on_delete=models.CASCADE)
  62. published = models.DateTimeField(default=datetime.datetime.now)
  63. ...
  64. If the front page, displaying the latest blog entries, only changes when you
  65. add a new blog entry, you can compute the last modified time very quickly. You
  66. need the latest ``published`` date for every entry associated with that blog.
  67. One way to do this would be::
  68. def latest_entry(request, blog_id):
  69. return Entry.objects.filter(blog=blog_id).latest("published").published
  70. You can then use this function to provide early detection of an unchanged page
  71. for your front page view::
  72. from django.views.decorators.http import condition
  73. @condition(last_modified_func=latest_entry)
  74. def front_page(request, blog_id): ...
  75. .. admonition:: Be careful with the order of decorators
  76. When ``condition()`` returns a conditional response, any decorators below
  77. it will be skipped and won't apply to the response. Therefore, any
  78. decorators that need to apply to both the regular view response and a
  79. conditional response must be above ``condition()``. In particular,
  80. :func:`~django.views.decorators.vary.vary_on_cookie`,
  81. :func:`~django.views.decorators.vary.vary_on_headers`, and
  82. :func:`~django.views.decorators.cache.cache_control` should come first
  83. because :rfc:`RFC 9110 <9110#section-15.4.5>` requires that the headers
  84. they set be present on 304 responses.
  85. Shortcuts for only computing one value
  86. ======================================
  87. As a general rule, if you can provide functions to compute *both* the ETag and
  88. the last modified time, you should do so. You don't know which headers any
  89. given HTTP client will send you, so be prepared to handle both. However,
  90. sometimes only one value is easy to compute and Django provides decorators
  91. that handle only ETag or only last-modified computations.
  92. The ``django.views.decorators.http.etag`` and
  93. ``django.views.decorators.http.last_modified`` decorators are passed the same
  94. type of functions as the ``condition`` decorator. Their signatures are::
  95. etag(etag_func)
  96. last_modified(last_modified_func)
  97. We could write the earlier example, which only uses a last-modified function,
  98. using one of these decorators::
  99. @last_modified(latest_entry)
  100. def front_page(request, blog_id): ...
  101. ...or::
  102. def front_page(request, blog_id): ...
  103. front_page = last_modified(latest_entry)(front_page)
  104. Use ``condition`` when testing both conditions
  105. ----------------------------------------------
  106. It might look nicer to some people to try and chain the ``etag`` and
  107. ``last_modified`` decorators if you want to test both preconditions. However,
  108. this would lead to incorrect behavior.
  109. ::
  110. # Bad code. Don't do this!
  111. @etag(etag_func)
  112. @last_modified(last_modified_func)
  113. def my_view(request): ...
  114. # End of bad code.
  115. The first decorator doesn't know anything about the second and might
  116. answer that the response is not modified even if the second decorators would
  117. determine otherwise. The ``condition`` decorator uses both callback functions
  118. simultaneously to work out the right action to take.
  119. Using the decorators with other HTTP methods
  120. ============================================
  121. The ``condition`` decorator is useful for more than only ``GET`` and
  122. ``HEAD`` requests (``HEAD`` requests are the same as ``GET`` in this
  123. situation). It can also be used to provide checking for ``POST``,
  124. ``PUT`` and ``DELETE`` requests. In these situations, the idea isn't to return
  125. a "not modified" response, but to tell the client that the resource they are
  126. trying to change has been altered in the meantime.
  127. For example, consider the following exchange between the client and server:
  128. #. Client requests ``/foo/``.
  129. #. Server responds with some content with an ETag of ``"abcd1234"``.
  130. #. Client sends an HTTP ``PUT`` request to ``/foo/`` to update the
  131. resource. It also sends an ``If-Match: "abcd1234"`` header to specify
  132. the version it is trying to update.
  133. #. Server checks to see if the resource has changed, by computing the ETag
  134. the same way it does for a ``GET`` request (using the same function).
  135. If the resource *has* changed, it will return a 412 status code,
  136. meaning "precondition failed".
  137. #. Client sends a ``GET`` request to ``/foo/``, after receiving a 412
  138. response, to retrieve an updated version of the content before updating
  139. it.
  140. The important thing this example shows is that the same functions can be used
  141. to compute the ETag and last modification values in all situations. In fact,
  142. you **should** use the same functions, so that the same values are returned
  143. every time.
  144. .. admonition:: Validator headers with non-safe request methods
  145. The ``condition`` decorator only sets validator headers (``ETag`` and
  146. ``Last-Modified``) for safe HTTP methods, i.e. ``GET`` and ``HEAD``. If you
  147. wish to return them in other cases, set them in your view. See
  148. :rfc:`9110#section-9.3.4` to learn about the distinction between setting a
  149. validator header in response to requests made with ``PUT`` versus ``POST``.
  150. Comparison with middleware conditional processing
  151. =================================================
  152. Django provides conditional ``GET`` handling via
  153. :class:`django.middleware.http.ConditionalGetMiddleware`. While being suitable
  154. for many situations, the middleware has limitations for advanced usage:
  155. * It's applied globally to all views in your project.
  156. * It doesn't save you from generating the response, which may be expensive.
  157. * It's only appropriate for HTTP ``GET`` requests.
  158. You should choose the most appropriate tool for your particular problem here.
  159. If you have a way to compute ETags and modification times quickly and if some
  160. view takes a while to generate the content, you should consider using the
  161. ``condition`` decorator described in this document. If everything already runs
  162. fairly quickly, stick to using the middleware and the amount of network
  163. traffic sent back to the clients will still be reduced if the view hasn't
  164. changed.