Invalidanti Memcached Tasti sul save () in Django
-
02-10-2019 - |
Domanda
Ho una vista in Django che utilizza memcached ai dati della cache per i panorami più altamente trafficate che si basano su un insieme relativamente statica di dati. La parola chiave è relativamente: ho bisogno di invalidare la chiave memcached per i dati di quel particolare URL quando è cambiato nel database. Per essere il più chiaro possibile, ecco la carne un' patate della vista (persona è un modello, 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
Quello che voglio fare è arrivare a quella variabile cache_key nella sua forma "non formattato", ma non sono sicuro di come fare questo -. Se può essere fatto a tutti
Nel caso in cui c'è già qualcosa per fare questo, ecco cosa voglio fare con esso (questo è da ipotetica del modello persona metodo di salvataggio)
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()
Sto pensando di fare un classe di visualizzazione per questa roba sorta, e con funzioni in esso come remove_cache
o generate_cache
da quando faccio questa roba sorta una molto . Vorrei che sia un'idea migliore? Se sì, come dovrei chiamare il punto di vista del URLconf se sono in una classe?
Soluzione
URLConf dovrebbe puntare a qualsiasi callable. Non c'è nessun requisito rigoroso per farlo puntare esattamente alla funzione. Si potrebbe implementare classe di base con i tuoi metodi di cache poi estenderlo:
class RealView(BaseViewWithCacheMethods):
def __call__(self, request):
if request.is_ajax():
return self.ajax_view()
return self.html_view()
definizione URLConf sarebbe qualcosa di simile:
from django.conf.urls.defaults import *
from views import RealView
urlpattrens = patterns('',
(r'^$', RealView()),
)