rest_framework学习(五)权限组件

权限组件

权限组件的目的是为了控制用户权限,实现不同权限访问不同资源

 rest_framework运行的权限组件的时间和认证组件相同

上一篇博客rest_framework学习(四)认证组件已经提到了,不再赘述。

当执行了self.check_permissions(request)方法,即执行该视图函数所有的权限组件

    def check_permissions(self, request):
        """
        Check if the request should be permitted.
        Raises an appropriate exception if the request is not permitted.
        """
        for permission in self.get_permissions():
            if not permission.has_permission(request, self):
                self.permission_denied(
                    request, message=getattr(permission, 'message', None)
                )

常用的rest_framework自带的权限组件

  • AllowAny
  • IsAuthenticated
  • IsAdminUser
  • IsAuthenticatedOrReadOnly

自定义权限组件

实现自定义权限组件必须要继承rest_framework.permissions.BasePermission

from rest_framework.permissions import BasePermission
class UserPermisson(BasePermission):
    message='您没权限查看'
    def has_permission(self, request, view):
        user_type=request.user.user_type
        if user_type==2: # 如果用户权限为2,可以访问
            return True
        else:
            return False

这里需要注意,有两种方法给函数添加权限功能:
第一种:

在对应函数下添加:

permission_classes = [MyAuth.UserPermisson,]
第二种:

在settings中全局配置:

REST_FRAMEWORK={

    'DEFAULT_PERMISSION_CLASSES':['app01.MyAuth.UserPermisson',]

}

配置之后所有的方法都需认证,当想局部禁用认证时,需在对应函数中添加下面这句

permission_classes = []

 

posted @ 2019-07-29 17:11  Wuliwawa  阅读(111)  评论(0编辑  收藏  举报