如何在Django Rest框架中为特定操作指定自定义身份验证和权限

时间:2019-10-25 11:52:00

标签: django django-rest-framework

我在django rest框架viewset中定义了以下代码:

class BookViewSet(viewsets.ModelViewSet):
    queryset = Book.objects.all()
    serializer_class = BookSerializer

    def list(self, request):
        return self.queryset.filter(user=self.request.user, is_published=True).order_by('-title')

    def retrieve(self, request, pk=None):
        queryset = Book.objects.all()
        book = get_object_or_404(queryset, pk=pk)
        serializer = BookSerializer(book)
        return Response(serializer.data)

    def get_permissions(self):
        """
        Instantiates and returns the list of permissions that this view requires.
        """
        if self.action == 'list':
            permission_classes = [IsAuthenticated]
        else:
            permission_classes = []
        return [permission() for permission in permission_classes]

    def get_authenticators(self):
        if self.action == 'list':
            authentication_classes = [TokenAuthentication]
        else:
            authentication_classes = []
        return [authentication() for authentication in authentication_classes]

因此,基本上我想要的是某人想要转到书的列表视图时,他必须通过令牌验证来验证自己,但是当某人只想检索一本书时,他不需要提供任何验证,他可以看到这本书的细节。

当我使用此代码时,由于某种原因self.action方法在get_authenticators中不起作用。

我该如何解决这个问题。下面是错误消息:

app_1  | Traceback (most recent call last):
app_1  |   File "/usr/local/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner
app_1  |     response = get_response(request)
app_1  |   File "/usr/local/lib/python3.7/site-packages/django/core/handlers/base.py", line 115, in _get_response
app_1  |     response = self.process_exception_by_middleware(e, request)
app_1  |   File "/usr/local/lib/python3.7/site-packages/django/core/handlers/base.py", line 113, in _get_response
app_1  |     response = wrapped_callback(request, *callback_args, **callback_kwargs)
app_1  |   File "/usr/local/lib/python3.7/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view
app_1  |     return view_func(*args, **kwargs)
app_1  |   File "/usr/local/lib/python3.7/site-packages/rest_framework/viewsets.py", line 114, in view
app_1  |     return self.dispatch(request, *args, **kwargs)
app_1  |   File "/usr/local/lib/python3.7/site-packages/rest_framework/views.py", line 480, in dispatch
app_1  |     request = self.initialize_request(request, *args, **kwargs)
app_1  |   File "/usr/local/lib/python3.7/site-packages/rest_framework/viewsets.py", line 135, in initialize_request
app_1  |     request = super().initialize_request(request, *args, **kwargs)
app_1  |   File "/usr/local/lib/python3.7/site-packages/rest_framework/views.py", line 382, in initialize_request
app_1  |     authenticators=self.get_authenticators(),
app_1  |   File "/wookie/books/views.py", line 60, in get_authenticators
app_1  |     if self.action == 'list':
app_1  | AttributeError: 'BookViewSet' object has no attribute 'action'

0 个答案:

没有答案