Showing posts with label cache. Show all posts
Showing posts with label cache. Show all posts
Jul 4, 2012
Templates caching
django-phased - Идея в том, чтобы рендерить шаблон в два прохода: сначала общие для всех закешированные куски шаблона, а потом специфичные для аутентифицированного пользователя части. Как уверяет автор, “this enables very fast generation of pages that have user-specific content”. Даже немного документации есть.
Labels:
cache,
optimization,
templates
May 12, 2012
Инвалидация кэша по событию с использованием декоратора
http://www.slideshare.net/MoscowDjango/django-12897658 слайд 32
gametags.py:
gametags.py:
@register.simple_tag
@cached(vary_on_args=True, locmem=True)
def games(platform=None, genre=None):
...
signals.py:
@receiver(post_save, sender=Game)
def inval_games(**kwargs):
invalidate(‘games.templatetags.gametags.games’)
http://pypi.python.org/pypi/django-cache-utils2
Labels:
cache
Nov 9, 2011
Django decorator/middleware cache key for given URL
import hashlib
from django.utils.encoding import iri_to_uri
from django.conf import settings
from django.utils.translation import get_language
def url_cache_key(url, language=None, key_prefix=None):
if key_prefix is None:
key_prefix = settings.CACHE_MIDDLEWARE_KEY_PREFIX
ctx = hashlib.md5()
path = hashlib.md5(iri_to_uri(url))
cache_key = 'views.decorators.cache.cache_page.%s.%s.%s.%s' % (
key_prefix, 'GET', path.hexdigest(), ctx.hexdigest())
if settings.USE_I18N:
cache_key += '.%s' % (language or get_language())
return cache_key
http://djangosnippets.org/snippets/2595/
Labels:
cache
Oct 20, 2011
Django caching
Полезная презентация: Cache rules everything around me
http://lanyrd.com/2011/djangocon-us/shbrr/
Instance Caching
http://lanyrd.com/2011/djangocon-us/shbrr/
django-cacheops
A slick app that supports automatic or manual queryset caching and automatic granular event-driven invalidation. It can also cache results of user functions and invalidate them by time or the same way as querysets. It uses redis as backend for ORM cache and redis or filesystem for simple time-invalidated one.django-newcache
Ничего особо полезного не нашел. Есть бэкенд для pylibmc, но такой уже имеется в джанге.johnny-cache
Кэширует все запросы. есть серьезные ограниченияAvoiding the database at all costs was not a goal, so different ordering clauses on the same dataset are considered different queries. Since invalidation happens at the table level, any table having been modified makes the cached query inaccessible
# cached, depends on `publisher` table
p = Publisher.objects.get(id=5)
# cached, depends on `book` and `publisher` table
Book.objects.all().select_related('publisher')
p.name = "Doubleday"
# write on `publisher` table, modifies publisher generation
p.save()
# the following are cache misses
Publisher.objects.get(id=5)
Book.objects.all().select_related('publisher')
django-autocache
В объект добавляется поле cache.Instance Caching
class Model(django.models.Model):
cache = autocache.CacheController()
field = django.models.TextField()
Model.objects.get(pk=27) # hits the database
Model.cache.get(27) # Tries cache first
Related Objects Caching
instance = Model.cache.get(pk=27)
related_things = instance.things_set.all() # hits the database
related_things = instance.cache.things_set # Tries cache first
Тоже есть ограниченияAutocache relies on the post_save and post_delete signals to keep your cache up to date. Performing operations that alter the database state without sending these signals will result in your cache becoming out of sync with your database.
cache-machine
Еще одна библиотека для автоматического кэширования и инвалидации. Ограничение - CachingManager должен быть менеджером модели по умолчаниюfrom django.db import models
import caching.base
class Zomg(caching.base.CachingMixin, models.Model):
val = models.IntegerField()
objects = caching.base.CachingManager()
django-cache-utils2
Django caching decorator + invalidate functionfrom cache_utils2 import cached, invalidate
@cached(60)
def foo(x, y=0):
print 'foo is called'
return x+y
foo(1, 2) # foo is called
foo(1, y=2)
foo(5, 6) # foo is called
foo(5, 6)
invalidate(foo, {'x': 1, 'y': 2})
foo(1, 2) # foo is called
foo(5, 6)
foo(x=2) # foo is called
foo(x=2)
Caching parsed templates
django.template.loaders.cached.Loader
https://docs.djangoproject.com/en/dev/ref/templates/api/#loader-types
https://docs.djangoproject.com/en/dev/ref/templates/api/#loader-types
Expire page from cache
from django.core.cache import cache
from django.http import HttpRequest
from django.utils.cache import get_cache_key
def expire_page(path):
request = HttpRequest()
request.path = path
key = get_cache_key(request)
if cache.has_key(key):
cache.delete(key)
http://djangosnippets.org/snippets/936/
Labels:
cache
Jul 29, 2011
Memcached
Установка
apt-get install memcached
apt-get install python-memcache
pylibmc работает быстрее но из-за того что написан на С вызывает дополнительные эксепшены, поэтому использовать надо осторожно
apt-get install python-pylibmc
Затем прописываем в settings.py
DATABASES = {
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
'LOCATION': '127.0.0.1:11211',
}
}
или для pylibmc
DATABASES = {
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.memcached.PyLibMCCache',
'LOCATION': '127.0.0.1:11211',
}
}
Сброс кэша
/etc/init.d/memcached restart
Или через телнет команду flush_all
Изменение конфигурации
vi /etc/memcached.conf
Jun 20, 2011
Сached decorator for functions
from django.core.cache import cache
from hashlib import sha256
def cached(ctime=3600):
def decr(func):
def wrp(*args,**kargs):
key = sha256(func.func_name+repr(args)+repr(kargs)).hexdigest()
res = cache.get(key)
if res is None:
res = func(*args,**kargs)
cache.set(key,res,ctime)
return res
return wrp
return decr
Subscribe to:
Posts (Atom)