Отмена использования Memcached ключей при сохранении () в Django
У меня есть представление в Django, которое использует memcached для кэширования данных для более интенсивно отслеживаемых представлений, которые полагаются на относительно статический набор данных. Ключевое слово относительно: мне нужно аннулировать ключ memcached для данных конкретного URL, когда он изменяется в базе данных. Чтобы быть как можно более ясным, вот мясо и "представление" (Person - это модель, cache - django.core.cache.cache):
def person_detail(request, slug):
if request.is_ajax():
cache_key = "%s_ABOUT_%s" % settings.SITE_PREFIX, slug
# Check the cache to see if we've already got this result made.
json_dict = cache.get(cache_key)
# Was it a cache hit?
if json_dict is None:
# That's a negative Ghost Rider
person = get_object_or_404(Person, display = True, slug = slug)
json_dict = {
'name' : person.name,
'bio' : person.bio_html,
'image' : person.image.extra_thumbnails['large'].absolute_url,
}
cache.set(cache_key)
# json_dict will now exist, whether it's from the cache or not
response = HttpResponse()
response['Content-Type'] = 'text/javascript'
response.write(simpljson.dumps(json_dict)) # Make sure it's all properly formatted for JS by using simplejson
return response
else:
# This is where the fully templated response is generated
Я хочу получить переменную cache_key в ее "неотформатированной" форме, но я не уверен, как это сделать - если это вообще возможно.
На случай, если уже есть что сделать, вот что я хочу сделать с этим (это из гипотетического метода сохранения модели Person)
def save(self):
# If this is an update, the key will be cached, otherwise it won't, let's see if we can't find me
try:
old_self = Person.objects.get(pk=self.id)
cache_key = # Voodoo magic to get that variable
old_key = cache_key.format(settings.SITE_PREFIX, old_self.slug) # Generate the key currently cached
cache.delete(old_key) # Hit it with both barrels of rock salt
# Turns out this doesn't already exist, let's make that first request even faster by making this cache right now
except DoesNotExist:
# I haven't gotten to this yet.
super(Person, self).save()
Я думаю о том, чтобы сделать класс представления для такого рода вещей и иметь такие функции, как remove_cache
или же generate_cache
так как я много занимаюсь этим сорта. Это была бы лучшая идея? Если так, как бы я вызывал представления в URLconf, если они в классе?
1 ответ
URLConf должен указывать на любой вызываемый. Там нет строгого требования, чтобы заставить его функционировать точно. Вы можете реализовать базовый класс с вашими методами кэширования, а затем расширить его:
class RealView(BaseViewWithCacheMethods):
def __call__(self, request):
if request.is_ajax():
return self.ajax_view()
return self.html_view()
Определение URLConf будет примерно таким:
from django.conf.urls.defaults import *
from views import RealView
urlpattrens = patterns('',
(r'^$', RealView()),
)