rest_framework 認證功能
from django.views import View from rest_framework.views import APIView from rest_framework.authentication import BasicAuthentication from rest_framework import exceptions from rest_framework.request import Request class MyAuthentication(object): def authenticate(self,request): token = request._request.GET.get(‘token‘) # 獲取用戶名和密碼,去數據校驗 if not token: raise exceptions.AuthenticationFailed(‘用戶認證失敗‘) return ("alex",None) def authenticate_header(self,val): pass class DogView(APIView): authentication_classes = [MyAuthentication,] def get(self,request,*args,**kwargs): print(request) print(request.user) self.dispatch ret= { ‘code‘:1000, ‘msg‘:‘xxx‘ } return HttpResponse(json.dumps(ret),status=201) def post(self,request,*args,**kwargs): return HttpResponse(‘創建Dog‘) def put(self,request,*args,**kwargs): return HttpResponse(‘更新Dog‘) def delete(self,request,*args,**kwargs): return HttpResponse(‘刪除Dog‘)
1. 認證
a. 問題1:有些API需要用戶登錄成功之後,才能訪問;有些無需登錄就能訪問。
b. 基本使用認證組件
解決:
a. 創建兩張表
b. 用戶登錄(返回token並保存到數據庫)
c. 認證流程原理
- 見圖示
d. 再看一遍源碼
1. 局部視圖使用&全局使用
2. 匿名是request.user = None
e. 內置認證類
1. 認證類,必須繼承:from rest_framework.authentication import BaseAuthentication
2. 其他認證類:BasicAuthentication
梳理:
1. 使用
- 創建類:繼承BaseAuthentication; 實現:authenticate方法
- 返回值:
- None,我不管了,下一認證來執行。
- raise exceptions.AuthenticationFailed(‘用戶認證失敗‘) # from rest_framework import exceptions
- (元素1,元素2) # 元素1賦值給request.user; 元素2賦值給request.auth
- 局部使用
from rest_framework.authentication import BaseAuthentication,BasicAuthentication
class UserInfoView(APIView):
"""
訂單相關業務
"""
authentication_classes = [BasicAuthentication,]
def get(self,request,*args,**kwargs):
print(request.user)
return HttpResponse(‘用戶信息‘)
- 全局使用:
REST_FRAMEWORK = {
# 全局使用的認證類
"DEFAULT_AUTHENTICATION_CLASSES":[‘api.utils.auth.FirstAuthtication‘,‘api.utils.auth.Authtication‘, ],
# "UNAUTHENTICATED_USER":lambda :"匿名用戶"
"UNAUTHENTICATED_USER":None, # 匿名,request.user = None
"UNAUTHENTICATED_TOKEN":None,# 匿名,request.auth = None
}
2. 源碼流程
- dispatch
- 封裝request
- 獲取定義的認證類(全局/局部),通過列表生成時創建對象。
- initial
- perform_authentication
request.user(內部循環....)
rest_framework 認證功能