原始碼流程:
dispatch函式執行
當尋找對應路由的視圖函式之前,首先執行 self.initialize_request(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
# 首先執行 self.initialize_request(request, *args, **kwargs)
# rest_framework首選對原始的request物件進行封裝,然后回傳新的request物件,
# Request(
# request,
# authenticators=self.get_authenticators(),
...
# )
原來的request物件初始化為:self._request,后面可以通過request._request獲取原始request物件
get_authenticators函式為獲取認證類的實體化物件
self.get_authenticators() = [auth() for auth in self.authentication_classes]
配置方法:
- settings 檔案全域配置:api_settings.DEFAULT_AUTHENTICATION_CLASSES
- 自定義配置 指定 authentication_classes即可
其次執行:self.initial(request, *args, **kwargs)
def initial(self, request, *args, **kwargs):
...
self.perform_authentication(request) # = request.user
...
@property
def user(self):
if not hasattr(self, '_user'):
with wrap_attributeerrors():
# 進行一層一層認證
self._authenticate()
return self._user
def _authenticate(self):
for authenticator in self.authenticators:
try:
user_auth_tuple = authenticator.authenticate(self) #呼叫認證類的authenticate方法
except exceptions.APIException:
self._not_authenticated()
raise
if user_auth_tuple is not None:
self._authenticator = authenticator
self.user, self.auth = user_auth_tuple #設定物件值,如果有回傳將退出回圈
return
自定義認證,繼承BaseAuthentication基類,例如:
class MyAuthentication(BaseAuthentication):
def authenticate(self, request):
token = request._request.GET.get("token")
if not token:
raise AuthenticationFailed
return ('donghao', 'auth auth') #設定到request.user , request.auth
def authenticate_header(self, request):
"""
Return a string to be used as the value of the `WWW-Authenticate`
header in a `401 Unauthenticated` response, or `None` if the
authentication scheme should return `403 Permission Denied` responses.
未認證時,回傳瀏覽器登陸彈窗,提交 類似 “Authorization: Basic YWRtaW46YWRtaW4=”的資料
"""
return 'Basic realm="api"'
rest_framework已經實作的 BasicAuthentication
auth = auth = request.META.get('HTTP_AUTHORIZATION', b'').split()
auth_parts = base64.b64decode(auth[1]).decode(HTTP_HEADER_ENCODING).partition(':')
userid, password = auth_parts[0], auth_parts[2]
匿名用戶設定,例如:
'UNAUTHENTICATED_USER': lambda: '匿名用戶',
'UNAUTHENTICATED_TOKEN': lambda: '匿名auth'
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/181238.html
標籤:Python
上一篇:Python初學篇二
下一篇:記一次不正經的爬蟲學習經歷
