У меня есть представление в 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, если они в классе?