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

How to optionally cache a view in Django

我在我的 Django 应用程序中创建了一个需要身份验证才能加载的视图。如果凭据不正确,则会发回错误 403 页面。因为我声明视图缓存在 urls.py 文件中,像这样...

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

...然后连错误页面都被缓存了。由于缓存是 29 天,我不能让这种情况发生。此外,如果页面被成功缓存,它会跳过我认为的身份验证步骤,从而使数据容易受到攻击。 我只希望 django 在结果成功时缓存页面,而不是在抛出错误时。此外,缓存页面只应在视图中进行身份验证后显示。我该怎么做?

我在 setting.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',
}

}

提前致谢

简单的解决方法。像这样更改您的 urls.py

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

然后像这样修改你的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

您是否也有兴趣切换到 memcached 而不是基于文件的缓存?