11.DRF-权限 (2)

(2)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. version, scheme = self.determine_version(request, *args, **kwargs) request.version, request.versioning_scheme = version, scheme # Ensure that the incoming request is permitted #4.实现认证 self.perform_authentication(request) #5.权限判断 self.check_permissions(request) self.check_throttles(request)

(3)check_permissions

里面有个has_permission这个就是我们自己写的权限判断

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) )

(4)get_permissions

def get_permissions(self): """ Instantiates and returns the list of permissions that this view requires. """ return [permission() for permission in self.permission_classes]

(5)permission_classes

11.DRF-权限

所以settings全局配置就如下

#全局 REST_FRAMEWORK = { "DEFAULT_PERMISSION_CLASSES":['API.utils.permission.SVIPPremission'], } 内置权限

django-rest-framework内置权限BasePermission

默认是没有限制权限

class BasePermission(object): """ A base class from which all permission classes should inherit. """ def has_permission(self, request, view): """ Return `True` if permission is granted, `False` otherwise. """ return True def has_object_permission(self, request, view, obj): """ Return `True` if permission is granted, `False` otherwise. """ return True

我们自己写的权限类,应该去继承BasePermission,修改之前写的permission.py文件

# utils/permission.py from rest_framework.permissions import BasePermission class SVIPPremission(BasePermission): message = "必须是SVIP才能访问" def has_permission(self,request,view): if request.user.user_type != 3: return False return True class MyPremission(BasePermission): def has_permission(self,request,view): if request.user.user_type == 3: return False return True 总结:

(1)使用

自己写的权限类:1.必须继承BasePermission类; 2.必须实现:has_permission方法

(2)返回值

True 有权访问

False 无权访问

(3)局部

permission_classes = [MyPremission,]

(4)全局

REST_FRAMEWORK = { #权限 "DEFAULT_PERMISSION_CLASSES":['API.utils.permission.SVIPPremission'], }

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wpwysd.html