Invalidation MeMCached Keys на Save () в Django
-
02-10-2019 - |
Вопрос
У меня есть вид в Django, который использует MEMCACHED, чтобы кэшировать данные для более высоких представлений с торговлей людьми, которые полагаются на относительно статический набор данных. Ключевое слово относительно: мне нужен неверный ключ memcached для этих конкретных данных URL, когда она изменяется в базе данных. Чтобы быть максимально ясным, вот мясо «картофель вида (человек - это модель, кэш - 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 в своей форме «неформатированной», но я не уверен, как это сделать - если это можно сделать вообще.
На всякий случай, если это уже что-то сделать, вот что я хочу с этим делать (это от гипотетического метода сохранения модели человека)
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, если они в классе?
Решение
URLCONF должен указывать на любой Callable. Там нет строгого требования, чтобы сделать его указывать на точку зрения точно. Вы можете реализовать базовый класс с вашими методами кэша, а затем расширить его:
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()),
)