Pregunta

Tengo una vista en Django que los usos MemCached a los datos de caché de las opiniones de trata más altamente que se basan en un conjunto relativamente estática de datos. La palabra clave es relativamente: Necesito invalidar la clave memcached para los datos de una URL concreta cuando se ha cambiado en la base de datos. Para ser lo más claro posible, aquí está la carne de un' patatas de la vista (la persona es un modelo, es django.core.cache.cache caché):

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

Lo que quiero hacer es llegar a esa variable cache_key en su forma "sin formato", pero no estoy seguro de cómo hacer esto -. Si se puede hacer en absoluto

Sólo en caso de que ya es algo para hacer esto, esto es lo que quiero hacer con ella (esto es de hipotética del modelo persona salve su método)

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()

Estoy pensando en hacer una clase de vista para estas cosas sorta, y que tiene funciones en ella como remove_cache o generate_cache como hago estas cosas sorta una mucho . ¿Sería una mejor idea? Si es así, ¿cómo iba a llamar a los puntos de vista en la URLconf si están en una clase?

¿Fue útil?

Solución

URLconf debe apuntar a cualquier exigible. No existe un requisito estricto para hacer que apunte exactamente a la función. Se podría aplicar clase base con sus métodos de caché y luego extenderla:

class RealView(BaseViewWithCacheMethods):
    def __call__(self, request):
        if request.is_ajax():
            return self.ajax_view()
        return self.html_view()

URLconf definición sería algo así:

from django.conf.urls.defaults import *
from views import RealView

urlpattrens = patterns('',
    (r'^$', RealView()),
)
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top