Django Rest 框架缓存 Headers
Django Rest Framework Cache Headers
我正在尝试在 CDN 中缓存我的一些 DRF api 调用。我需要以下 headers Cache-Control:public, max-age=XXXX
当您使用传统的 django 模板时,这非常简单,您只需添加 @cache_page() @cache_control(public=True) 装饰器,但对于 DRF ,我找不到任何类似的东西。内存缓存中有很多内容,我已经有了,但我真的很想让 CDN 一起减轻我服务器的负载,我想缓存生成的查询集。
我也在使用 modelViewSets,如果这对任何事情都很重要的话:
class EventViewSet(viewsets.ModelViewSet):
serializer_class = EventViewSet
permission_classes = (permissions.IsAuthenticatedOrReadOnly,)
pagination_class = pagination.LimitOffsetPagination
filter_backends = (filters.DjangoFilterBackend, filters.SearchFilter,)
filter_class = EventFilter
search_fields = ('name','city','state')
def get_queryset(self):
更新:我从来没有在 Django 或 Django Rest Framework 中解决问题。我最终在我们的 nginx conf 文件中设置了 headers。
你试过了吗:
from django.utils.decorators import method_decorator
from django.views.decorators.cache import cache_control
class EventViewSet(viewsets.ModelViewSet):
@method_decorator(cache_control(private=False, max_age=xxxx)
def dispatch(self, request, *args, **kwargs):
return super(EventViewSet, self).dispatch(request, *args, **kwargs)
@method_decorator
can be applied to the view class。当提供 name
参数时,它将将该命名方法包装在 class 的实例中。你想要的是:
from django.utils.decorators import method_decorator
from django.views.decorators.cache import cache_control
@method_decorator(cache_control(public=True, max_age=xxxx), name='dispatch')
class EventViewSet(viewsets.ModelViewSet):
...
我正在尝试在 CDN 中缓存我的一些 DRF api 调用。我需要以下 headers Cache-Control:public, max-age=XXXX
当您使用传统的 django 模板时,这非常简单,您只需添加 @cache_page() @cache_control(public=True) 装饰器,但对于 DRF ,我找不到任何类似的东西。内存缓存中有很多内容,我已经有了,但我真的很想让 CDN 一起减轻我服务器的负载,我想缓存生成的查询集。
我也在使用 modelViewSets,如果这对任何事情都很重要的话:
class EventViewSet(viewsets.ModelViewSet):
serializer_class = EventViewSet
permission_classes = (permissions.IsAuthenticatedOrReadOnly,)
pagination_class = pagination.LimitOffsetPagination
filter_backends = (filters.DjangoFilterBackend, filters.SearchFilter,)
filter_class = EventFilter
search_fields = ('name','city','state')
def get_queryset(self):
更新:我从来没有在 Django 或 Django Rest Framework 中解决问题。我最终在我们的 nginx conf 文件中设置了 headers。
你试过了吗:
from django.utils.decorators import method_decorator
from django.views.decorators.cache import cache_control
class EventViewSet(viewsets.ModelViewSet):
@method_decorator(cache_control(private=False, max_age=xxxx)
def dispatch(self, request, *args, **kwargs):
return super(EventViewSet, self).dispatch(request, *args, **kwargs)
@method_decorator
can be applied to the view class。当提供 name
参数时,它将将该命名方法包装在 class 的实例中。你想要的是:
from django.utils.decorators import method_decorator
from django.views.decorators.cache import cache_control
@method_decorator(cache_control(public=True, max_age=xxxx), name='dispatch')
class EventViewSet(viewsets.ModelViewSet):
...