简体   繁体   中英

How to have different permission classes for methods in DRF

I have a view similar to this:

from django.http import HttpResponse
from rest_framework import generics

class MyView(generics.ListCreateAPIView):

    def get_queryset(self):
        # <view logic>
        return HttpResponse('result')

    def post(self, request):
        # <view logic x2>
        return HttpResponse('message_post_template')

And I would like the GET request to have the permission class of IsAuthenticated and the POST request should have a permission class of HasAPIKey from Django REST Framework API Key . How can I do this?

I tried doing permission_classes = [IsAuthenticated | HasAPIKey] permission_classes = [IsAuthenticated | HasAPIKey] but that would be too lenient because it would allow the functions to work if the other permission other than the one required is available.

from django.http import HttpResponse
from rest_framework import generics

class MyView(generics.ListCreateAPIView):

    def get_permissions(self):
        method = self.request.method
        if method == 'POST':
           return [HasAPIKey()]
        else:
           return [IsAuthenticated()]

    def get_queryset(self):
        # <view logic>
        return HttpResponse('result')

    def post(self, request):
        # <view logic x2>
        return HttpResponse('message_post_template')

Reference:
https://github.com/encode/django-rest-framework/blob/dff9759555eefef67c552f175d04bb7d8381e919/rest_framework/views.py#L274

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM