日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

Django Rest Framework源码剖析(二)-----权限

發(fā)布時間:2024/9/5 编程问答 34 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Django Rest Framework源码剖析(二)-----权限 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
一、簡介

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

二、基本使用

這里繼續(xù)使用之前的示例,加入相應的權(quán)限,這里先介紹使用示例,然后在分析權(quán)限源碼

1.在django 項目下新建立目錄utils,并建立permissions.py,添加權(quán)限控制:

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

?

2.在訂單視圖中使用

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

urls.py

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

models.py

from django.db import modelsclass 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.驗證:訂單業(yè)務同樣使用user_type=1的用戶進行驗證,這里使用工具postman發(fā)送請求驗證,結(jié)果如下:證明我們的權(quán)限生效了。

三、權(quán)限源碼剖析

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

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 = argsself.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.封裝requestrequest = self.initialize_request(request, *args, **kwargs)self.request = requestself.headers = self.default_response_headers # deprecate?try:#2.認證self.initial(request, *args, **kwargs)# Get the appropriate handler methodif 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_allowedresponse = 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.執(zhí)行inital方法,initial方法中執(zhí)行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 requestneg = 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.實現(xiàn)認證 self.perform_authentication(request)#5.權(quán)限判斷 self.check_permissions(request)self.check_throttles(request)

3.當執(zhí)行完perform_authentication方法認證通過時候,這時候就進入了本篇文章主題--權(quán)限(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(): #循環(huán)對象get_permissions方法的結(jié)果,如果自己沒有,則去父類尋找,if not permission.has_permission(request, self): #判斷每個對象中的has_permission方法返回值(其實就是權(quán)限判斷),這就是為什么我們需要對權(quán)限類定義has_permission方法self.permission_denied( request, message=getattr(permission, 'message', None) #返回無權(quán)限信息,也就是我們定義的message共有屬性)

4.從上源碼中我們可以看出,perform_authentication方法中循環(huán)get_permissions結(jié)果,并逐一判斷權(quán)限,所以需要分析get_permissions方法返回結(jié)果,以下是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] #與權(quán)限一樣采用列表生成式獲取每個認證類對象

5.get_permissions方法中尋找權(quán)限類是通過self.permission_class字段尋找,和認證類一樣默認該字段在全局也有配置,如果我們視圖類中已經(jīng)定義,則使用我們自己定義的類。

class APIView(View):# The following policies may be set at either globally, or per-view.renderer_classes = api_settings.DEFAULT_RENDERER_CLASSESparser_classes = api_settings.DEFAULT_PARSER_CLASSESauthentication_classes = api_settings.DEFAULT_AUTHENTICATION_CLASSESthrottle_classes = api_settings.DEFAULT_THROTTLE_CLASSES permission_classes = api_settings.DEFAULT_PERMISSION_CLASSES #權(quán)限控制content_negotiation_class = api_settings.DEFAULT_CONTENT_NEGOTIATION_CLASSmetadata_class = api_settings.DEFAULT_METADATA_CLASSversioning_class = api_settings.DEFAULT_VERSIONING_CLASS

6.承接check_permissions方法,當認證類中的has_permission()方法返回false時(也就是認證不通過),則執(zhí)行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的權(quán)限源碼到此結(jié)束,相對于認證源碼簡單一些。

四、內(nèi)置權(quán)限驗證類

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

#路徑:rest_framework.permissions ##基本權(quán)限驗證 class BasePermission(object)##允許所有 class AllowAny(BasePermission)##基于django的認證權(quán)限,官方示例 class IsAuthenticated(BasePermission):##基于django admin權(quán)限控制 class IsAdminUser(BasePermission)##也是基于django admin class IsAuthenticatedOrReadOnly(BasePermission) .....
五、總結(jié)

1.使用方法:

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

2.配置:

###全局使用 REST_FRAMEWORK = {#權(quán)限"DEFAULT_PERMISSION_CLASSES":['API.utils.permission.MyPremission'], }##單一視圖使用,為空代表不做權(quán)限驗證 permission_classes = [MyPremission,] ###優(yōu)先級 單一視圖>全局配置

?

轉(zhuǎn)載于:https://www.cnblogs.com/wdliu/p/9102960.html

總結(jié)

以上是生活随笔為你收集整理的Django Rest Framework源码剖析(二)-----权限的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。