cache_page with Class Based Views

前端 未结 8 1947
孤独总比滥情好
孤独总比滥情好 2020-12-14 06:23

I\'m trying to do cache_page with class based views (TemplateView) and i\'m not able to. I followed instructions here:

Django--URL Caching Failing for Class Based Vi

相关标签:
8条回答
  • 2020-12-14 07:23

    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).

    0 讨论(0)
  • 2020-12-14 07:25

    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
    
    0 讨论(0)
提交回复
热议问题