【问题标题】:Django Rest Framework Cache HeadersDjango Rest 框架缓存头
【发布时间】:2017-03-12 06:48:14
【问题描述】:

我正在尝试在 CDN 中缓存我的一些 DRF api 调用。我需要以下标头 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):

【问题讨论】:

    标签: python django caching django-rest-framework cdn


    【解决方案1】:

    @method_decoratorcan be applied to the view class。当提供name 参数时,它将将该命名方法包装在该类的实例中。你想要的是类似的东西:

    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):
        ...
    

    【讨论】:

      【解决方案2】:

      你试过了吗:

      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)
      

      【讨论】:

        【解决方案3】:

        更新:我从未解决过 Django 或 Django Rest Framework 中的问题。我最终在我们的 nginx conf 文件中设置了标题。

        【讨论】:

          猜你喜欢
          • 2013-04-07
          • 2021-08-19
          • 2018-12-08
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-12-27
          相关资源
          最近更新 更多