64
According to the caching docs, the correct way to cache a CBV in the URLs is:
from django.views.decorators.cache import cache_page
url(r'^my_url/?$', cache_page(60*60)(MyView.as_view())),
Note that the answer you linked to is out of date. The old way of using the decorator has been removed (changeset).
35
You can simply decorate the class itself instead of overriding the dispatch method or using a mixin.
For example
from django.views.decorators.cache import cache_page
from django.utils.decorators import method_decorator
@method_decorator(cache_page(60 * 5), name='dispatch')
class ListView(ListView):
...
Django docs on decorating a method within a class based view.
- [Django]-What is a good value for CONN_MAX_AGE in Django?
- [Django]-Django celery task: Newly created model DoesNotExist
- [Django]-How to use less css with django?
32
yet another good example CacheMixin
from cyberdelia github
class CacheMixin(object):
cache_timeout = 60
def get_cache_timeout(self):
return self.cache_timeout
def dispatch(self, *args, **kwargs):
return cache_page(self.get_cache_timeout())(super(CacheMixin, self).dispatch)(*args, **kwargs)
usecase:
from django.views.generic.detail import DetailView
class ArticleView(CacheMixin, DetailView):
cache_timeout = 90
template_name = "article_detail.html"
queryset = Article.objects.articles()
context_object_name = "article"
- [Django]-Debugging Apache/Django/WSGI Bad Request (400) Error
- [Django]-How do I reuse HTML snippets in a django view
- [Django]-Python 3 list(dictionary.keys()) raises error. What am I doing wrong?
13
You can add it as a class decorator and even add multiple using a list:
@method_decorator([vary_on_cookie, cache_page(900)], name='dispatch')
class SomeClass(View):
...
- [Django]-How to annotate Count with a condition in a Django queryset
- [Django]-Celery missed heartbeat (on_node_lost)
- [Django]-Difference between django-redis-cache and django-redis for redis caching with Django?
3
I created this little mixin generator to do the caching in the views
file, instead of in the URL conf:
def CachedView(cache_time=60 * 60):
"""
Mixing generator for caching class-based views.
Example usage:
class MyView(CachedView(60), TemplateView):
....
:param cache_time: time to cache the page, in seconds
:return: a mixin for caching a view for a particular number of seconds
"""
class CacheMixin(object):
@classmethod
def as_view(cls, **initkwargs):
return cache_page(cache_time)(
super(CacheMixin, cls).as_view(**initkwargs)
)
return CacheMixin
- [Django]-How to get URL of current page, including parameters, in a template?
- [Django]-Why does django's prefetch_related() only work with all() and not filter()?
- [Django]-Aggregate (and other annotated) fields in Django Rest Framework serializers
3
Yet another answer, we found this to be simplest and is specific to template views.
class CachedTemplateView(TemplateView):
@classonlymethod
def as_view(cls, **initkwargs): #@NoSelf
return cache_page(15 * 60)(super(CachedTemplateView, cls).as_view(**initkwargs))
- [Django]-Django serializer inherit and extend fields
- [Django]-Python vs C#/.NET — what are the key differences to consider for using one to develop a large web application?
- [Django]-Django – run a function every x seconds
3
Would like to add this:
If you need to use multiple decorators for cache like vary_on_headers and cache_page together, here is one way I did:
class CacheHeaderMixin(object):
cache_timeout = int(config('CACHE_TIMEOUT', default=300))
# cache_timeout = 60 * 5
def get_cache_timeout(self):
return self.cache_timeout
def dispatch(self, *args, **kwargs):
return vary_on_headers('Authorization')(cache_page(self.get_cache_timeout())(super(CacheHeaderMixin, self).dispatch))(*args, **kwargs)
This way cache is stored and it varies for different Authorization header (JWT). You may use like this for a class based view.
class UserListAPIView(CacheHeaderMixin, ListAPIView):
serializer_class = UserSerializer
def get_queryset(self):
return CustomUser.objects.all()
- [Django]-Internal Server Error with Django and uWSGI
- [Django]-Folder Structure for Python Django-REST-framework and Angularjs
- [Django]-No module named pkg_resources
2
I didn’t found a good cache solution for class based views and created my own: https://gist.github.com/svetlyak40wt/11126018
It is a mixin for a class. Add it before the main base class and implement method get_cache_params like that:
def get_cache_params(self, *args, **kwargs):
return ('some-prefix-{username}'.format(
username=self.request.user.username),
3600)
- [Django]-URL-parameters and logic in Django class-based views (TemplateView)
- [Django]-Can I use a database view as a model in Django?
- [Django]-Django 1.7 upgrade error: AppRegistryNotReady: Apps aren't loaded yet
0
Here’s my variation of the CachedView()
mixin – I don’t want to cache the view if the user is authenticated, because their view of pages will be unique to them (e.g. include their username, log-out link, etc).
class CacheMixin(object):
"""
Add this mixin to a view to cache it.
Disables caching for logged-in users.
"""
cache_timeout = 60 * 5 # seconds
def get_cache_timeout(self):
return self.cache_timeout
def dispatch(self, *args, **kwargs):
if hasattr(self.request, 'user') and self.request.user.is_authenticated:
# Logged-in, return the page without caching.
return super().dispatch(*args, **kwargs)
else:
# Unauthenticated user; use caching.
return cache_page(self.get_cache_timeout())(super().dispatch)(*args, **kwargs)
- [Django]-Can I make STATICFILES_DIR same as STATIC_ROOT in Django 1.3?
- [Django]-How can I serialize a queryset from an unrelated model as a nested serializer?
- [Django]-Automated django receive hook on server: respond to collectstatic with "yes"