rest_framework 权限流程
权限流程
权限流程与认证流程非常相似,只是后续操作稍有不同
当用户访问是 首先执行dispatch函数,当执行当第二部时:
#2.处理版本信息 处理认证信息 处理权限信息 对用户的访问频率进行限制 self.initial(request, *args, **kwargs)
进入到initial方法:
def initial(self, request, *args, **kwargs): """ Runs anything that needs to occur prior to calling the method handler. """ self.format_kwarg = self.get_format_suffix(**kwargs) # Perform content negotiation and store the accepted info on the request neg = self.perform_content_negotiation(request) request.accepted_renderer, request.accepted_media_type = neg # Determine the API version, if versioning is in use. #2.1处理版本信息 version, scheme = self.determine_version(request, *args, **kwargs) request.version, request.versioning_scheme = version, scheme # Ensure that the incoming request is permitted #2.2处理认证信息 self.perform_authentication(request) #2.3处理权限信息 self.check_permissions(request) #2.4对用户的访问频率进行限制 self.check_throttles(request
#处理权限信息 self.check_permissions(request)
下面 开始 权限的具体分析:
进入到check_permissions函数中
#检查权限 def check_permissions(self, request): """ Check if the request should be permitted. Raises an appropriate exception if the request is not permitted. """ #elf.get_permissions()得到的是一个权限对象列表 for permission in self.get_permissions(): #在自定义的Permission中has_permission方法是必须要有的 #判断当前has_permission返回的是True,False,还是抛出异常 #如果是True则表示权限通过,False执行下面代码 if not permission.has_permission(request, self): #为False的话则抛出异常,当然这个异常返回的提示信息是英文的,如果我们想让他显示我们自定义的提示信息 #我们重写permission_denied方法即可 self.permission_denied( #从自定义的Permission类中获取message(权限错误提示信息),一般自定义的话都建议写上,如果没有则为默认的(英文提示) request, message=getattr(permission, 'message', None) )
查看permission_denied方法(如果has_permission返回True则不执行该方法)
def permission_denied(self, request, message=None): """ If request is not permitted, determine what kind of exception to raise. """ if request.authenticators and not request.successful_authenticator: #没有登录提示的错误信息 raise exceptions.NotAuthenticated() #一般是登陆了但是没有权限提示 raise exceptions.PermissionDenied(detail=message)
局部权限
permissions.py
# 局部权限 from rest_framework.permissions import BasePermission class SVIPPermissions(BasePermission): # 提示信息 message = "滚!您没有权限" def has_permission(self,request,view): # 获取到认证的返回值 user_obj=request.user.user if user_obj.user_type==3: return True else: return False
view.py
class BookViewsSet(viewsets.ModelViewSet): # 权限 permission_classes=[SVIPPermissions] queryset = Book.objects.all() serializer_class = BookModelSerializer
全局权限
permissions.py
# 局部权限
from rest_framework.permissions import BasePermission
class SVIPPermissions(BasePermission):
# 提示信息
message = "滚!您没有权限"
def has_permission(self,request,view):
# 获取到认证的返回值
user_obj=request.user.user
if user_obj.user_type==3:
return True
else:
return False
settings.py
REST_FRAMEWORK={ "DEFAULT_PERMISSION_CLASSES":["api.servise.permission.SVIPPermissions"], }
待续