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

1、簡介

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

2、基本使用

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

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

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

 

2.在訂單視圖中使用app

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.pypost

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發送請求驗證,結果以下:證實咱們的權限生效了。ui

3、權限源碼剖析

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

dispatch()url

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則開始進行認證spa

 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的權限源碼到此結束,相對於認證源碼簡單一些。

4、內置權限驗證類

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)
.....
5、總結

1.使用方法:

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

2.配置:

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

##單一視圖使用,爲空表明不作權限驗證
permission_classes = [MyPremission,] 


###優先級
單一視圖>全局配置
相關文章
相關標籤/搜索