动态更改页面缓存

时间:2018-10-20 09:29:06

标签: django

我想动态缓存页面

通常我们有:

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

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

大量研究源代码后,我发现如果数据未更新,如何显示缓存页面,否则显示修改后的数据视图

不要在url.py中使用cache_page

from django.middleware.cache import CacheMiddleware

@login_required

someview(request, slug=None)

    ######  data_updated
    # Check the conditions data modified is updated or not
    data_updated = True/False
    ######

    cachemiddleware = CacheMiddleware(cache_timeout=60*15)

    if data_updated:

        #######
            # RUN all the code for view
            # response = ..........
        #######


        # this is required because if the url is already cached it will be false
        request._cache_update_cache = True

        return cachemiddleware.process_response(request, response)

    else:

        result = cachemiddleware.process_request(request)

        if result is not None:
            return result
        else:

            #######
            # RUN all the code for view
            # response = ..........
            #######

            return cachemiddleware.process_response(request, response)