- 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
- Stuff by NixonDash 1 month ago
- Add custom fields to the built-in Group model by jmoppel 3 months ago
- Month / Year SelectDateWidget based on django SelectDateWidget by pierreben 6 months, 2 weeks ago
- Python Django CRUD Example Tutorial by tuts_station 7 months ago
- Browser-native date input field by kytta 8 months, 2 weeks ago
Comments
Please login first before commenting.