使用@api_view函数视图

时间:2015-04-22 10:21:44

标签: python django django-rest-framework

我想缓存我的API响应。我正在使用Django Rest Framework,并且希望@cache_response()使用来自drf extensions的{​​{1}}装饰器。

我正在关注以下示例:http://chibisov.github.io/drf-extensions/docs/#cache-response只有基于类的视图的示例。

当我像这样申请时:

@api_view(http_method_names=['GET'])
@cache_response()
def my_view(request, some_arg):
    (...)

我最终得到了错误:

inner() takes at least 2 arguments (1 given)

完整追溯:

Traceback:

    File "/Users/andi/.virtualenvs/adfoo/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
      112.                     response = wrapped_callback(request, *callback_args, **callback_kwargs)
    File "/Users/andi/.virtualenvs/adfoo/lib/python2.7/site-packages/django/views/decorators/csrf.py" in wrapped_view
      57.         return view_func(*args, **kwargs)
    File "/Users/andi/.virtualenvs/adfoo/lib/python2.7/site-packages/django/views/generic/base.py" in view
      69.             return self.dispatch(request, *args, **kwargs)
    File "/Users/andi/.virtualenvs/adfoo/lib/python2.7/site-packages/rest_framework/views.py" in dispatch
      407.             response = self.handle_exception(exc)
    File "/Users/andi/.virtualenvs/adfoo/lib/python2.7/site-packages/rest_framework/views.py" in dispatch
      404.             response = handler(request, *args, **kwargs)
    File "/Users/andi/.virtualenvs/adfoo/lib/python2.7/site-packages/rest_framework/decorators.py" in handler
      51.             return func(*args, **kwargs)

    Exception Type: TypeError at /api/foo/1/exhibitors/
    Exception Value: inner() takes at least 2 arguments (1 given)

我该如何正确应用?

DRF扩展为装饰方法的requirenet指定装饰器:

1)它应该是继承自rest_framework.views.APIView的类方法

2)它应该返回rest_framework.response.Response实例。

考虑到第1点)我不确定它是否可能......

这是drf @api_view decorator https://github.com/tomchristie/django-rest-framework/blob/master/rest_framework/decorators.py

的来源

这是drf扩展程序@cache_response decorator https://github.com/chibisov/drf-extensions/blob/master/rest_framework_extensions/cache/decorators.py

的来源

2 个答案:

答案 0 :(得分:1)

您不能将drf-extension的cache_response()用于基于函数的视图。请检查此issue

答案 1 :(得分:0)

正如 Ashish 所提到的cache_response drf-extensions装饰器用于APIView类的方法。但即使在那种情况下我也不会推荐它。因为Django已经支持为方法使用函数装饰器。

所以有两种方式:

1 - 使用Django Rest Framework api_view装饰器和Django cache_page装饰器 Django函数视图

from django.views.decorators.cache import cache_page
from rest_framework.decorators import api_view


@cache_page(60 * 15)
@api_view(['GET', 'POST'])
def snippet_list(request):
    ...

2 - 使用Django method_decorator装饰器基于Django Rest Framework类的视图

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


@method_decorator(cache_page(60 * 15), name='dispatch')
class SnippetListView(APIView):
    ...

never_cache等同样如此。