CachedPaginator

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
from django.core.cache import cache
from django.core.paginator import Paginator, Page


class CachedPaginator(Paginator):
    """A paginator that caches the results on a page by page basis."""
    def __init__(self, object_list, per_page, cache_key, cache_timeout=300, orphans=0, allow_empty_first_page=True):
        super(CachedPaginator, self).__init__(object_list, per_page, orphans, allow_empty_first_page)
        self.cache_key = cache_key
        self.cache_timeout = cache_timeout

    def page(self, number):
        """
        Returns a Page object for the given 1-based page number.
        
        This will attempt to pull the results out of the cache first, based on
        the number of objects per page and the requested page number. If not
        found in the cache, it will pull a fresh list and then cache that
        result.
        """
        number = self.validate_number(number)
        cached_object_list = cache.get(self.build_cache_key(number), None)
        
        if cached_object_list is not None:
            page = Page(cached_object_list, number, self)
        else:
            page = super(CachedPaginator, self).page(number)
            # Since the results are fresh, cache it.
            cache.set(self.build_cache_key(number), page.object_list, self.cache_timeout)
        
        return page
    
    def build_cache_key(self, page_number):
        """Appends the relevant pagination bits to the cache key."""
        return "%s:%s:%s" % (self.cache_key, self.per_page, page_number)

More like this

  1. extends_default by daniellindsley 4 years, 6 months ago
  2. Paginator TemplateTag by trbs 5 years, 1 month ago
  3. Simple Paginator Function by goodsanket 3 years, 3 months ago
  4. template + cache = crazy delicious by jacobian 6 years ago
  5. Modelaware json serializer by fivethreeo 6 years, 2 months ago

Comments

(Forgotten your password?)