首页 > 解决方案 > 动态更改页面缓存

问题描述

我想动态缓存一个页面

一般我们有:

from django.views.decorators.cache import cache_page

@cache_page(60 * 15)
def my_view(request):
    ...

或者

from django.views.decorators.cache import cache_page

urlpatterns = [
    path('foo/<int:code>/', cache_page(60 * 15)(my_view)),
]

但是在视图里面我想根据一些逻辑来判断,改变缓存机制(比如清除缓存并重新启动新缓存)

def my_view(request):
   if some logic is true:
      then clear cache_page()

      execute the view login
      response = ......

      add response to cache_page()
      return response

   else:
      return the old cached page

标签: django

解决方案


我认为在您的用例Conditional View Processing中最合适,它可以满足您的需求,只是它依赖Etag标头告诉浏览器内容没有更改。更多关于Conditional view processinghttps://docs.djangoproject.com/en/2.1/topics/conditional-view-processing/


推荐阅读