一.权限源码分析
1.同样请求到达视图时候,先执行APIView的dispatch方法,以下源码是我们在认证篇已经解读过了:
def dispatch(self, request, *args, **kwargs):
"""
`.dispatch()` is pretty much the same as Django's regular dispatch,
but with extra hooks for startup, finalize, and exception handling.
"""
self.args = args
self.kwargs = kwargs
#对原始request进行加工,丰富了一些功能
#Request(
# request,
# parsers=self.get_parsers(),
# authenticators=self.get_authenticators(),
# negotiator=self.get_content_negotiator(),
# parser_context=parser_context
# )
#request(原始request,[BasicAuthentications对象,])
#获取原生request,request._request
#获取认证类的对象,request.authticators
#1.封装request
request = self.initialize_request(request, *args, **kwargs)
self.request = request
self.headers = self.default_response_headers # deprecate?
try:
#2.认证
self.initial(request, *args, **kwargs)
# Get the appropriate handler method
if request.method.lower() in self.http_method_names:
handler = getattr(self, request.method.lower(),
self.http_method_not_allowed)
else:
handler = self.http_method_not_allowed
response = handler(request, *args, **kwargs)
except Exception as exc:
response = self.handle_exception(exc)
self.response = self.finalize_response(request, response, *args, **kwargs)
return self.response
2.执行inital方法,initial方法中执行perform_authentication则开始进行认证
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.当执行完perform_authentication方法认证通过时候,这时候就进入了权限(check_permissions方法),下面是check_permissions方法源码:
def check_permissions(self, request):
"""
Check if the request should be permitted.
Raises an appropriate exception if the request is not permitted.
"""
#循环get_permissions()方法的结果,如果自己没有,则去父类寻找
for permission in self.get_permissions():
#判断每个对象中的has_permission方法返回值(其实就是权限判断),这就是为什么我们需要对权限类定义has_permission方法,如果不通过则执行下面的方法
if not permission.has_permission(request, self): #这里需要传两个参数request和self,这里的self为视图类对象
self.permission_denied(
request, message=getattr(permission, 'message', None)
) #返回无权限信息,也就是我们定义的message共有属性
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.get_permissions方法中寻找权限类是通过self.permission_class字段寻找,和认证类一样默认该字段在全局也有配置,如果我们视图类中已经定义,则使用我们自己定义的类。
class APIView(View):
# The following policies may be set at either globally, or per-view.
renderer_classes = api_settings.DEFAULT_RENDERER_CLASSES
parser_classes = api_settings.DEFAULT_PARSER_CLASSES
authentication_classes = api_settings.DEFAULT_AUTHENTICATION_CLASSES
throttle_classes = api_settings.DEFAULT_THROTTLE_CLASSES
permission_classes = api_settings.DEFAULT_PERMISSION_CLASSES #权限控制
content_negotiation_class = api_settings.DEFAULT_CONTENT_NEGOTIATION_CLASS
metadata_class = api_settings.DEFAULT_METADATA_CLASS
versioning_class = api_settings.DEFAULT_VERSIONING_CLASS
6.承接check_permissions方法,当认证类中的has_permission()方法返回false时(也就是认证不通过),则执行self.permission_denied(),以下是self.permission_denied()源码:
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) # 如果定义了message属性,则抛出属性值
7.认证不通过,则至此django rest framework的权限源码到此结束,相对于认证源码简单一些。
二.自定义权限类
1.urls.py
url(r'^api/v1/orders/$', views.OrderView.as_view()),
2.views.py 部分代码
ORDER_DICT = {
1: {
'name': "iphone",
'price': 6000,
'count': 2
},
2: {
'name': "DELL",
'price': 8000,
'count': 1
},
3: {
'name': "MAC",
'price': 10000,
'count': 3
}
}
class OrderView(views.APIView):
"""
查看订单(SVIP可以访问)
"""
permission_classes=[Mypermision,]
# throttle_classes = [UserVisitThrottle,]
def get(self, request, *args, **kwargs):
print(request.user)
print(request.auth)
ret={'code':1000,'msg':None}
try:
ret['data']=ORDER_DICT
except Exception as e:
pass
return JsonResponse(ret)
3.utils.py —>permision.py
from rest_framework.permissions import BasePermission
#匿名用户无权访问
class Mypermision(BasePermission):
message = '无权访问'
def has_permission(self, request, view):
if request.user: # 判断是有名还是匿名用户
return True
else:
return False
#只有SVIP用户可以访问
class ManagePermission(BasePermission):
message = '无权访问'
def has_permission(self, request, view):
if request.user.user_type == 3:
return True
return False
三.配置自定义认证类
1.局部使用,在视图类中进行配置
permission_classes=[Mypermision,]
2.全局使用,在settings里面配置
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': ['app01.utils.permision.Mypermision', ], # 全局配置,