認證原始碼分析
位置 :
APIVIew----》dispatch方法---》self.initial(request, *args, **kwargs)---->有認證,權限,頻率三個版塊
分析:
只讀認證原始碼: self.perform_authentication(request)---》
self.perform_authentication(request)就一句話:request.user,需要去drf的Request物件中找user屬性(方法)---》
Request類中的user方法,剛開始來,沒有_user,走 self._authenticate()

核心:Request類的 _authenticate(self):
1.在需要進行認證的視圖類中添加(認證類是自己寫的類,該類繼承了BaseAuthentication):

2.此時apiview里的 authentication_classes就變成了自己第一步在視圖函式類里定義的了,而不會去自己的組態檔里找

3.然后正常執行到apiview里的dispatch方法:

4.dispatch方法內部又呼叫了initialize_request方法,回傳了一個新的request物件

5.authenticators這個的值是get_authenticators()方法的回傳值:回傳值是一個個自己定義的繼承了BaseAuthentication類的認證類物件

6.Request類中的authenticators變成了自定義類的物件

7.在繼續走apiview里的dispatch方法里的initial方法

8.進入認證模塊的方法

9.進入新封裝request物件里


10.核心_authenticate方法
def _authenticate(self):
# self是Request物件,所以去Request物件里找authenticators,
# 最后self.authenticators的結果就是一個串列,串列里面是一個個自定義認證類的物件
for authenticator in self.authenticators:
try:
# 此時authenticator就是認證類的物件,物件呼叫了authenticate方法,這個方法是需要我們在認證類里重新寫的
# 這個方法有兩個回傳值
user_auth_tuple = authenticator.authenticate(self)
except exceptions.APIException:
self._not_authenticated()
raise
if user_auth_tuple is not None:
self._authenticator = authenticator
# 這兩個回傳值給了Request物件,就是request.user和request.auth(這就是為什么要求自己重新寫的authenticate方法要有兩個回傳值了)
self.user, self.auth = user_auth_tuple
return
self._not_authenticated()
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/519267.html
標籤:其他
上一篇:【python】待君有余暇,看春賞櫻花,這不得來一場浪漫的櫻花旅~
下一篇:5 位元組碼檔案結構
