I've recently migrated all views in one of my Django projects to the new class-based ones. For classic function-based Django views there's a handy decorator django.views.decorators.http.condition
that can be used to bypass the whole view processing if there's a cached copy matching the conditions that you've specified. I've searched everywhere in the docs and in the source code but can't find any implementation of this for the new class-based views.
So my question is: How would you suggest that I implement conditional view processing for class-based views?
You may use the following:
Caching is a complex matter, but recent trends (both for data-/fragment-caching in the server, and for asset caching, in browsers) show that it is better not to spend time in solving the cache invalidation problem, but just do what described in this article:
http://37signals.com/svn/posts/3113-how-key-based-cache-expiration-works
Real-world example of this technique applied to Django:
http://www.rossp.org/blog/2012/feb/29/fragment-caching/
It looks like there isn't a nice answer to this problem yet. For decorators that just set function attributes (e.g.
csrf_exempt
), it is enough to apply them to the view class'sdispatch
method, but that obviously doesn't work for thecondition
decorator, since they expect the first function argument to be a request object rather thanself
.Two ways you could achieve this include:
Apply the decorator to the generated view function. The generic view functionality really boils down to a way of building view functions from classes, so applying the decorator late might be an option. Something like this:
This has the disadvantage that you don't have access to the view class from the functions you pass to the
condition
decorator. It is also not very convenient if you're calling theas_view
method in the urlconf.Delegate to a simple function you can apply decorators to inside your view's
dispatch
method. Something like this:This one has the benefit that you have access to the view class instance when applying the decorator, so you could use instance methods for your cache validation functions. A downside is that the decorator will be run every time the view is invoked, but that doesn't look like a problem for this particular decorator.
Both solutions have their problems though, so perhaps it would be worth filing a bug report or asking on the django-users mailing list about how these two concepts should best be combined.