1. 程式人生 > >Django Rest Framework源碼剖析(二)-----權限

Django Rest Framework源碼剖析(二)-----權限

www. 基於 framework suffix 生效 ted AI try exce

一、簡介

在上一篇博客中已經介紹了django rest framework 對於認證的源碼流程,以及實現過程,當用戶經過認證之後下一步就是涉及到權限的問題。比如訂單的業務只能VIP才能查看,所以這時候需要對權限進行控制。下面將介紹DRF的權限控制源碼剖析。

二、基本使用

這裏繼續使用之前的示例,加入相應的權限,這裏先介紹使用示例,然後在分析權限源碼

1.在django 項目下新建立目錄utils,並建立permissions.py,添加權限控制:

class MyPremission(object):
    message = "您不是會員無權訪問"
    def
has_permission(self,request,view): if request.user.user_type == 1: ## user_type 為1代表普通用戶,則不能查看 return False return True

2.在訂單視圖中使用

class OrderView(APIView):
    ‘‘‘查看訂單‘‘‘
    from utils.permissions import MyPremission
    authentication_classes = [Authentication,]    #
添加認證 permission_classes = [MyPremission,] #添加權限 def get(self,request,*args,**kwargs): #request.user #request.auth ret = {code:1000,msg:"你的訂單已經完成",data:"買了一個mac"} return JsonResponse(ret,safe=True)

urls.py

from django.conf.urls import url
from django.contrib import
admin from app01 import views urlpatterns = [ url(r^api/v1/auth, views.AuthView.as_view()), url(r^api/v1/order, views.OrderView.as_view()), ]

models.py

from django.db import models

class UserInfo(models.Model):
    user_type_choice = (
        (1,"普通用戶"),
        (2,"會員"),
    )
    user_type = models.IntegerField(choices=user_type_choice)
    username = models.CharField(max_length=32,unique=True)
    password = models.CharField(max_length=64)


class UserToken(models.Model):
    user = models.OneToOneField(to=UserInfo)
    token = models.CharField(max_length=64)

3.驗證:訂單業務同樣使用user_type=1的用戶進行驗證,這裏使用工具postman發送請求驗證,結果如下:證明我們的權限生效了。

技術分享圖片

三、權限源碼剖析

1.同樣請求到達視圖時候,先執行APIView的dispatch方法,以下源碼是我們在認證篇已經解讀過了:

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.
        """
        for permission in self.get_permissions():   #循環對象get_permissions方法的結果,如果自己沒有,則去父類尋找,
            if not permission.has_permission(request, self): #判斷每個對象中的has_permission方法返回值(其實就是權限判斷),這就是為什麽我們需要對權限類定義has_permission方法
                self.permission_denied(                       
                    request, message=getattr(permission, message, None) #返回無權限信息,也就是我們定義的message共有屬性
                )

4.從上源碼中我們可以看出,perform_authentication方法中循環get_permissions結果,並逐一判斷權限,所以需要分析get_permissions方法返回結果,以下是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的權限源碼到此結束,相對於認證源碼簡單一些。

四、內置權限驗證類

django rest framework 提供了內置的權限驗證類,其本質都是定義has_permission()方法對權限進行驗證:

#路徑:rest_framework.permissions
##基本權限驗證
class BasePermission(object)

##允許所有
class AllowAny(BasePermission)

##基於django的認證權限,官方示例
class IsAuthenticated(BasePermission):

##基於django admin權限控制
class IsAdminUser(BasePermission)

##也是基於django admin
class IsAuthenticatedOrReadOnly(BasePermission)
.....
五、總結

1.使用方法:

  • 繼承BasePermission類(推薦)
  • 重寫has_permission方法
  • has_permission方法返回True表示有權訪問,False無權訪問

2.配置:

###全局使用
REST_FRAMEWORK = {
   #權限
    "DEFAULT_PERMISSION_CLASSES":[API.utils.permission.MyPremission],
}

##單一視圖使用,為空代表不做權限驗證
permission_classes = [MyPremission,] 


###優先級
單一視圖>全局配置

Django Rest Framework源碼剖析(二)-----權限