在 Django 中通过 save() 使 Memcached 键失效

发布于 2024-08-30 20:25:25 字数 2150 浏览 3 评论 0原文

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

我正在考虑为这种东西创建一个视图类,并在其中包含像 < code>remove_cache 或 generate_cache 因为我经常做这种事情。那是一个更好的主意吗?如果是这样,如果 URLconf 中的视图在一个类中,我将如何调用它们?

I've got a view in Django that uses memcached to cache data for the more highly trafficked views that rely on a relatively static set of data. The key word is relatively: I need invalidate the memcached key for that particular URL's data when it's changed in the database. To be as clear as possible, here's the meat an' potatoes of the view (Person is a model, cache is 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

What I want to do is get at that cache_key variable in it's "unformatted" form, but I'm not sure how to do this--if it can be done at all.

Just in case there's already something to do this, here's what I want to do with it (this is from the Person model's hypothetical save method)

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

I'm thinking about making a view class for this sorta stuff, and having functions in it like remove_cache or generate_cache since I do this sorta stuff a lot. Would that be a better idea? If so, how would I call the views in the URLconf if they're in a class?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

浅笑依然 2024-09-06 20:25:25

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

URLConf should point to any callable. There's no strict requirement to make it point to function exactly. You could implement base class with your cache methods then extend it:

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

URLConf definition would be something like that:

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

urlpattrens = patterns('',
    (r'^
, RealView()),
)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文