視圖函數中加上認證功能,流程見下圖
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
|
import hashlib import time def get_random(name): md = hashlib.md5() md.update(bytes( str (time.time()),encoding = 'utf-8' )) md.update(bytes(name,encoding = 'utf-8' )) return md.hexdigest() from rest_framework.views import APIView class Login(APIView): authentication_classes = [AuthLogin] def post( self , request, * args, * * kwargs): response = { 'status' : 100 , 'msg' : None } name = request.data.get( 'name' ) pwd = request.data.get( 'pwd' ) user = models.User.objects. filter (name = name, password = pwd).first() if user: response[ 'msg' ] = '登陸成功' # 隨機字符串可以是用戶名加當前時間生成的mds token = get_random(name) # 如果有記錄,就只需要更新,不需要重新插入 # models.UserToken.objects.create(token=token,user=user) # 查詢 更新 # user_agent models.UserToken.objects.update_or_create(user = user, defaults = { 'token' : token}) response[ 'token' ] = token else : response[ 'status' ] = 101 response[ 'msg' ] = '用戶名或密碼錯誤' return Response(response) |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
from rest_framework.permissions import BasePermission from rest_framework.exceptions import NotAuthenticated from app01 import models # BaseAuthentication class AuthLogin(BaseAuthentication): def authenticate( self , request): # 封裝后的request token = request.GET.get( 'token' ) # print(token) ret = models.UserToken.objects. filter (token = token).first() if ret: return ret.user,token else : raise NotAuthenticated( '您沒有登陸' ) |
在def initial(self, request, *args, **kwargs):函數中找到認證功能
流程總結:
- dispatch 方法里self.initial里面有個認證組件self.perform_authentication(request)
- 到了APIview 返回了request.user (封裝后的Request)
- 去request類里找user方法,被包裝成了屬性,里面執行了一個方法,self._authticate方法
- self._authticate方法里從自己的authenticators一個一個的取東西,authenticators
- 于是查看authenticators,是初始化的時候init傳過來了,self.authenticators = authenticators or()
- 到dispatch里找初始化的時候,也就是APIView的initialize_request方法傳了self.authenticators,里面是一個get_authenticators的方法
- self.authentication_classes 是[類1,類2,類3]一個一個取,加括號執行。生成一個一個對象.最后返回到前面的Request的_authenticate方法
- 拿到對象之后,執行user_auth_tuple = authenticator.authenticate(self)
- 注意authenticate是需要在視圖函數中自己定義的,self.user, self.auth = user_auth_tuple返回兩個值,流程結束。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。
原文鏈接:https://www.cnblogs.com/wanlei/p/10426844.html