【问题标题】:Invalidating Memcached Keys on save() in Django在 Django 中使保存()上的 Memcached 键无效
【发布时间】:2010-04-28 19:46:25
【问题描述】:

我在 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_cachegenerate_cache 之类的函数,因为我经常很多 做这类东西。那会是一个更好的主意吗?如果是这样,如果它们在一个类中,我将如何调用 URLconf 中的视图?

【问题讨论】:

    标签: django django-models memcached django-views cache-invalidation


    【解决方案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()),
    )
    

    【讨论】:

    • 这是我迄今为止所采用的方法,取得了有限的成功,而且进展顺利。完成后我会在这里发布课程。
    猜你喜欢
    • 2011-05-10
    • 1970-01-01
    • 2021-03-10
    • 1970-01-01
    • 2012-08-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多