0

我在 Django 中有一个视图,它使用 memcached 为依赖于相对静态数据集的流量更高的视图缓存数据。关键字是相对的:当数据库中发生更改时,我需要使特定 URL 数据的 memcached 键无效。为了尽可能清楚,这是视图的肉和土豆(Person 是一个模型,缓存是 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 中的视图?

4

1 回答 1

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()),
)
于 2010-05-03T07:48:22.063 回答