LoginSignup
12
7

More than 5 years have passed since last update.

Django REST Framework:1つのAPIViewの中でリクエストメソッド毎にpermission_classesを分ける

Last updated at Posted at 2019-01-18

1つのAPIViewの中でGETはどのユーザでもリクエストできるAllowAnyにしたいけれど、POSTとかDELETEは認証済みのIsAuthenticated、もしくは独自のパーミッションに設定したい、というケースが発生した

単純にGETだけはAllowAnyにして、他のメソッドはIsAuthenticatedにしたい場合は permission_classes = (IsAuthenticatedOrReadOnly,) を使用すれば良い

しかし、上記の場合だと、独自で定義したパーミッションまでカバーできないので、今回は以下の方法で対応してみた

from rest_framework.views import APIView
from rest_framework.permissions import AllowAny
from hogehogehogehoge import MyCustomPermission

class MyAPIView(APIView):
    def get_permissions(self):
        self.permission_classes = (AllowAny, )
        if self.request.method == 'DELETE':
            self.permission_classes = (MyCustomPermission,)
        return super(MyAPIView, self).get_permissions()

    def get(self, request):
        ....

    def delete(self, request, pk):
        ....

このようにすると、getメソッドは誰でもリクエストができるAllowAnyとして、deleteメソッドは独自定義した MyCustomPermission をパーミッションとして採用することができる
他にも選択肢はある(IsAuthenticatedOrReadOnly を拡張したり、継承したクラスを作るとか)けれど、その方法の一つとして...

12
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
12
7