【问题标题】:Different Permissions using decorators for each methods inside ModelViewset methods for "list", "create" , "retrieve", "update"对“list”、“create”、“retrieve”、“update”的 ModelViewset 方法中的每个方法使用装饰器的不同权限
【发布时间】:2019-06-23 15:13:18
【问题描述】:

我想使用装饰器为 ModelViewset 类的不同方法添加不同的权限。

我试过了:

class abcd(viewsets.ModelViewSet):

    @permission_classes(IsAuthenticated,))
    def list(self, request, format=None):
        try:


    @permission_classes(CustomPermission,))
    def create(self, request, format=None):
        try:

但它不起作用。 我也尝试使用@method_decorator。那也没用。

我知道我们可以通过以下方式进行:

def get_permissions(self):
    if self.action == 'create':
        return [IsAuthenticated(), ]        
    return super(abcd, self).get_permissions()

但我想知道我们是否可以使用 Django Rest 框架的装饰器来实现这一点。

【问题讨论】:

    标签: django django-rest-framework django-views python-decorators django-permissions


    【解决方案1】:

    示例代码见官方页面。
    所以最好不要使用 self.request.method 而是 self.aciton 属性。

    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 = [IsAdmin]
        return [permission() for permission in permission_classes]
    

    https://www.django-rest-framework.org/api-guide/viewsets/#introspecting-viewset-actions

    【讨论】:

      【解决方案2】:

      ModelViewSet 继承 Mixin 类和 GenericAPIViewlistcreate 方法来自 Mixins,因此使用 permission_classes 进行装饰将不起作用。相反,您可以尝试在 APIView 中覆盖 get_permissions

      def get_permissions(self):
          if self.request.method == "GET":
              return [IsAuthenticated()]
          elif self.request.method == "POST":
              return [CustomPermission()]
          return [permission() for permission in self.permission_classes]
      
      

      注意:我不确定上面的代码是否有效

      【讨论】:

      • 应该可以,不过使用了与dict映射非常相似的东西。关于偏好,还可以检查self.actionlistcreate 等。
      • 我知道def get_permissions(self):。但是不知道是继承自Mixins和generics的。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-21
      • 2021-07-15
      • 2015-03-07
      • 1970-01-01
      相关资源
      最近更新 更多