| 1 | =============== |
| 2 | View Decorators |
| 3 | =============== |
| 4 | |
| 5 | .. module:: django.views.decorators.http |
| 6 | |
| 7 | The decorators in the ``django.views.decorators.http`` module can be applied |
| 8 | to views to process certain HTTP headers. |
| 9 | |
| 10 | |
| 11 | |
| 12 | ``require_http_methods`` |
| 13 | ======================== |
| 14 | |
| 15 | .. function:: require_http_methods(request_method_list) |
| 16 | |
| 17 | This decorator to make a view only accept particular request methods. |
| 18 | Usage:: |
| 19 | from django.views.decorators.http import require_http_methods |
| 20 | |
| 21 | @require_http_methods(["GET", "POST"]) |
| 22 | def my_view(request): |
| 23 | # I can assume now that only GET or POST requests make it this far |
| 24 | # ... |
| 25 | |
| 26 | Note that request methods should be in uppercase. |
| 27 | |
| 28 | Two shorcuts are defined, ``require_GET`` and ``require_POST``, which limit |
| 29 | the request method to GET and POST respectively. |
| 30 | |
| 31 | ``condition`` |
| 32 | ============= |
| 33 | |
| 34 | .. function:: condition(etag_func=None, last_modified_func=None) |
| 35 | |
| 36 | The ``condition`` decorator support conditional retrieval for a view |
| 37 | function. |
| 38 | |
| 39 | The parameters are callables to compute the ETag and last modified time for |
| 40 | the requested resource, respectively. The callables are passed the same |
| 41 | parameters as the view itself. The Etag function should return a string (or |
| 42 | None if the resource doesn't exist), whilst the last_modified function |
| 43 | should return a datetime object (or None if the resource doesn't exist). |
| 44 | |
| 45 | If both parameters are provided, all the preconditions must be met before |
| 46 | the view is processed. |
| 47 | |
| 48 | This decorator will either pass control to the wrapped view function or |
| 49 | return an HTTP 304 response (unmodified) or 412 response (preconditions |
| 50 | failed), depending upon the request method. |
| 51 | |
| 52 | Any behavior marked as "undefined" in the HTTP spec (e.g. ``If-none-match`` |
| 53 | plus ``If-modified-since`` headers) will result in the view function being |
| 54 | called. |
| 55 | |
| 56 | Two shortcuts are defined for the common cases. |
| 57 | |
| 58 | .. function:: etag(etag_func) |
| 59 | |
| 60 | This decorator provides only an etag function. |
| 61 | |
| 62 | .. function:: last_modified(last_modified_func) |
| 63 | |
| 64 | This decorator provides only a last-modified function. |