【问题标题】:Caching a ViewSet with DRF : TypeError: _wrapped_view()使用 DRF 缓存 ViewSet:TypeError: _wrapped_view()
【发布时间】:2019-01-01 02:36:40
【问题描述】:

我只想对 ViewSet 使用缓存太慢 :(,使用 Django REST 框架。

我已经这样做了:

...
from django.utils.decorators import method_decorator
from django.views.decorators.cache import cache_page
from django.views.decorators.vary import vary_on_cookie
...
class PRPKViewSet(viewsets.ModelViewSet):
    serializer_class = PrpkSerializer
    queryset = Prpk.objects.all().order_by('begin')
    # Authentification !
    permission_classes = (IsAuthenticated,)
    # Only 'get' method
    http_method_names = ['get']

    # Cache requested url for each user for 2 hours
    # @method_decorator(vary_on_cookie)
    @method_decorator(cache_page(60*2))
    def get_queryset(self):
        """ allow rest api to filter by submissions """
        queryset = Prpk.objects.all().order_by('begin')
        highway = self.request.query_params.get('highway', None)
        if highway is not None:
            queryset = queryset.filter(highway=highway)

        return queryset

但是在查询时,我有这个错误:

TypeError: _wrapped_view() missing 1 required positional argument: 'request'

Memcached 已安装。

那么,我可以只缓存一个 ViewSet(不使用扩展吗?)?

非常感谢。

F.

【问题讨论】:

    标签: django caching django-rest-framework memcached


    【解决方案1】:

    装饰dispatch 而不是get_queryset

    @method_decorator(cache_page(60*2))
    def dispatch(self, request, *args, **kwargs):
        return super().dispatch(request, *args, **kwargs)
    

    【讨论】:

    • 嗨,谢谢。我刚刚在“get_queryset”上方添加了“dispatch”函数,但出现了这个错误:“如果 response.streaming 或 response.status_code 不在 (200, 304):AttributeError: 'NoneType' object has no attribute 'streaming' "
    • 我的错:缺少“返回”:)。第一次查询:11 秒,第二次调用:431 毫秒 :)。它正在工作。现在,请问如何查看当前缓存的页面?
    • @fabrice true,我错过了return,已修复。查看 stackoverflow.com/questions/9048257/… 以了解如何获取 chached 页面,因为这是一个不同的问题。
    • 如何使cache_page 无效?并测试它是否真的有效
    • 重要提示:如果您对视图集进行了身份验证,那么缓存检查将在身份验证检查之前完成,这非常危险。
    猜你喜欢
    • 1970-01-01
    • 2016-11-24
    • 2016-09-13
    • 2017-08-23
    • 1970-01-01
    • 2014-11-03
    • 2022-11-04
    • 2018-09-30
    • 1970-01-01
    相关资源
    最近更新 更多