Django Rest Framework custom permissions per view

前端 未结 3 2016
-上瘾入骨i
-上瘾入骨i 2021-02-10 00:36

I want to create permissions in Django Rest Framework, based on view + method + user permissions.

Is there a way to achieve this without manually writing each permission

3条回答
  •  南旧
    南旧 (楼主)
    2021-02-10 01:19

    Well, the first step could be done easy with DRF. See http://www.django-rest-framework.org/api-guide/permissions#custom-permissions.

    You must do something like that:

    from functools import partial
    
    from rest_framework import permissions
    
    class MyPermission(permissions.BasePermission):
    
        def __init__(self, allowed_methods):
            super().__init__()
            self.allowed_methods = allowed_methods
    
        def has_permission(self, request, view):
            return request.method in self.allowed_methods
    
    
    class ExampleView(APIView):
        permission_classes = (partial(MyPermission, ['GET', 'HEAD']),)
    

提交回复
热议问题