如何在Django视图类中设置缓存控制标头(无缓存) [英] How to set cache control headers in a Django view class (no-cache)

查看:75
本文介绍了如何在Django视图类中设置缓存控制标头(无缓存)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

现在这花了我一些时间来弄清楚,所以我将对其进行自我解答.我想在视图上为Django中的一个特定页面禁用浏览器缓存.如果视图是一个函数,则有一些信息,而如果它是一个类,则没有此信息.我不想使用中间件,因为只有一个特定的视图我不想被缓存.

Now this took me some time to figure out, so I will self-answer it. I wanted to disable browser caching for one specific page in Django on a View. There is some information how to do this if the view is a function, but not if it's a class. I did not want to use a middleware, because there was only one specific view that I didn't want to be cached.

推荐答案

有装饰器可以执行此操作,例如 django.views中的 cache_control never_cache .decorators.cache

There are decorators to do this, for example cache_control and never_cache in django.views.decorators.cache

对于功能,您只需像这样装饰功能

For a function, you would just decorate the function like this

@never_cache
def my_view1(request):
    # your view code

@cache_control(max_age=3600)
def my_view2(request):
    # your view code

请参见 https://docs.djangoproject.com/en/3.0/topics/cache/#controlling-cache-using-other-headers

现在,如果您的视图是一个类,则必须应用另一个我已经知道的使用身份验证的方法,但是没有建立连接.该类还有另一个装饰器来装饰类中的函数

Now, if your view is a class, you have to apply another method, that I already knew of for using authentication, but did not make the connection. There is another decorator for the class to decorate functions within the class

from django.utils.decorators import method_decorator
from django.views.decorators.cache import never_cache

decorators = [never_cache,]

@method_decorator(decorators, name='dispatch')
class MyUncachedView(FormView):
    # your view code

这将使用上面定义的 decorators 列表中指定的装饰器装饰表单方法 dispatch .不必执行调度方法,顺便说一句.

This will decorate the form method dispatch with the decorators specified in the decorators list, defined above. You don't have to implement the dispatch method, btw.

还有其他方法可以执行此操作,请参见此处:

There are also other variations to do that, see here: https://docs.djangoproject.com/en/3.0/topics/class-based-views/intro/#decorating-the-class

这篇关于如何在Django视图类中设置缓存控制标头(无缓存)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆