The `Resource` class is a way of writing a Django view as a class. I've done this as part of an effort to write easier-to-understand RESTful apps, as this allows the grouping of similar views as different types of operation on a resource. Essentially, the solution goes something like this:
* Views have to be callables which return HttpResponse objects.
* The problem with views as classes is that calling a view class returns an instance of the view class, not HttpResponse.
* Solution: have the VC (view class) a subclass of HttpResponse. This way, 'calling' the class will return a HttpResponse instance.
The `Resource` class performs a dispatch on the request method, so that a resource can be retrieved, created/updated and deleted by writing 'get', 'put' and 'delete' methods on a subclass of `Resource`.
A general `Book` class shows how this might work for the case of 'books' in a system:
class Book(Resource):
def get(self, request, book_name):
book = myapp.models.Book.objects.get(name=book_name)
return render_to_response('book_template.html', {'book': book})
def put(self, request, book_name):
new_book, created = get_or_create(myapp.models.Book, name=book_name)
new_book.data = request.raw_post_data
if created:
return HttpResponse(status=201)
return HttpResponse(status=200)
def delete(self, request, book_name):
book = myapp.models.Book.objects.get(name=book_name)
book.delete()
return HttpResponse()
As you can see, classes can return responses, and these will be merged back into the returned response by the `Resource._update` method.
- rest
- resource
- view-class
- view-as-a-class