| 557 | .. _supporting-other-http-methods: |
| 558 | |
| 559 | Supporting other HTTP methods |
| 560 | ----------------------------- |
| 561 | |
| 562 | Suppose somebody wants to access our book library over HTTP using the views |
| 563 | as an API. The API client would connect every now and then and download book |
| 564 | data for the books published since last visit. But if no new books appeared |
| 565 | since then, it is a waste of CPU time and bandwidth to fetch the books from |
| 566 | database, render a full response and send it to the client. It might be |
| 567 | preferable to ask the API when the most recent book was published. |
| 568 | |
| 569 | We define the URL to book list in the URLconf:: |
| 570 | |
| 571 | from django.conf.urls import patterns |
| 572 | from books.views import BookListView |
| 573 | |
| 574 | urlpatterns = patterns('', |
| 575 | (r'^books/$', BookListView.as_view()), |
| 576 | ) |
| 577 | |
| 578 | And the view:: |
| 579 | |
| 580 | from django.http import HttpResponse |
| 581 | from django.views.generic import ListView |
| 582 | from books.models import Book |
| 583 | |
| 584 | class BookListView(ListView): |
| 585 | |
| 586 | model = Book |
| 587 | |
| 588 | def head(self, *args, **kwargs): |
| 589 | last_book = self.get_queryset().latest('publication_date') |
| 590 | response = HttpResponse('') |
| 591 | # RFC 1123 date format |
| 592 | response['Last-Modified'] = last_book.publication_date.strftime('%a, %d %b %Y %H:%M:%S GMT') |
| 593 | return response |
| 594 | |
| 595 | If the view is accessed from a ``GET`` request, a plain-and-simple object |
| 596 | list is returned in the response (using ``book_list.html`` template). But if |
| 597 | the client issues a ``HEAD`` request, the response has an empty body and |
| 598 | the ``Last-Modified`` header indicates when the most recent book was published. |
| 599 | Based on this information, the client may or may not download the full object |
| 600 | list. |
| 601 | |