Login

CachedPaginator

Author:
daniellindsley
Posted:
November 7, 2008
Language:
Python
Version:
1.0
Score:
2 (after 2 ratings)

A subclassed version of the standard Django Paginator (django.core.paginator.Paginator) that automatically caches pages as they are requested. Very useful if your object list is expensive to compute.

MIT licensed.

 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. Template tag - list punctuation for a list of items by shapiromatron 3 months ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 3 months, 1 week ago
  3. Serializer factory with Django Rest Framework by julio 10 months, 1 week ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 10 months, 3 weeks ago
  5. Help text hyperlinks by sa2812 11 months, 3 weeks ago

Comments

Please login first before commenting.