如何在Django中选择性地缓存视图

时间:2022-05-14 18:48:30

I have created a view in my Django app that requires authentication to load. If the credentials are incorrect, then an error 403 page is sent back. Since I declared the view to be cached in the urls.py file, like this...

我在我的Django应用程序中创建了一个视图,它需要进行身份验证才能加载。如果凭证不正确,则返回一个错误403页。因为我声明了要缓存到url中的视图。py文件,这样……

    url(r'^example/example-url/(?P<special_id>\d+)/$',
        cache_page(60 * 60 * 24 * 29, cache='site_cache')(views.example_view),
        name="example"),

... then even the error pages are being cached. Since the cache is for 29 days, I can't have this happen. Furthermore, if a the page is successfully cached, it skips the authentication steps I take in my view, leaving the data vulnerable. I only want django to cache the page when the result is a success, not when an error is thrown. Also, the cached page should only be presented after authentication in the view. How can I do this?

…然后,甚至错误页面也被缓存。因为缓存是29天,所以我不能这样做。此外,如果页面被成功缓存,它将跳过我在视图中采取的身份验证步骤,从而使数据变得脆弱。我只希望django在结果成功时缓存页面,而不是在抛出错误时缓存页面。此外,缓存的页面应该只在视图中的身份验证之后显示。我该怎么做呢?

My cache settings in setting.py:

我的缓存设置在设置。py:

CACHES = {
'default': {
    'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
    'LOCATION': 'unique-snowflake',
},
'site_cache': {
    'BACKEND': 'django.core.cache.backends.filebased.FileBasedCache',
    'LOCATION': '/var/tmp/django_cache',
}

}

}

Thanks in advance

谢谢提前

1 个解决方案

#1


1  

Simple work around. Change your urls.py like this.

简单的工作。改变你的url。py是这样的。

url(r'^example/example-url/(?P<special_id>\d+)/$',
        views.example_view,
        name="example"),

Then modify your example_view like this:

然后修改example_view如下:

def example_view(request, sepcial_id):
    if request.user.is_authenticated():
        key = 'exmpv{0}'.format(special_id)

        resp = cache.get(key)
        if not resp:
             # your complicated queries

             resp = render('yourtemplate',your context)
             cache.set(key, resp)
        return resp
     else:
         # handle unauthorized situations

Can I also interest you in switching to memcached instead of file based caching?

我还能让您对切换到memcached而不是基于文件的缓存感兴趣吗?

#1


1  

Simple work around. Change your urls.py like this.

简单的工作。改变你的url。py是这样的。

url(r'^example/example-url/(?P<special_id>\d+)/$',
        views.example_view,
        name="example"),

Then modify your example_view like this:

然后修改example_view如下:

def example_view(request, sepcial_id):
    if request.user.is_authenticated():
        key = 'exmpv{0}'.format(special_id)

        resp = cache.get(key)
        if not resp:
             # your complicated queries

             resp = render('yourtemplate',your context)
             cache.set(key, resp)
        return resp
     else:
         # handle unauthorized situations

Can I also interest you in switching to memcached instead of file based caching?

我还能让您对切换到memcached而不是基于文件的缓存感兴趣吗?