目录
一、BaseAuthentication - 用于拦截请求,在视图函数钱执行相应认证方法
1-1 登陆相关视图函数 - 使用Token字符串存储数据库模拟session
1-2 BaseAuthentication 登陆认证 - drfAuth.py
二、认证配置 - authentication_classes
一、BaseAuthentication - 用于拦截请求,在视图函数钱执行相应认证方法
总结:
- 认证类
- 认证类必须单独存放在py文件内,若防止在view内,使用全局配置时候,无法使用
- 必须继承 BaseAuthentication
- from rest_framework.authentication import BaseAuthentication
- 认证类内必须重写 authenticate(self, request) 方法,request参数必须传入
- 若后续有其他认证类需要执行,必须返回空!!
- 若后续不无其他认证类需要执行,则返回两个值 - 对应DRF内Request对象User类内_authenticate方法执行
- 若认证失败,抛出 exceptions.APIException 异常
- from rest_framework import exceptions
- 执行认证的视图类中配置 authentication_classes = [drfAuth.LoginAuth, ]
1-1 登陆相关视图函数 - 使用Token字符串存储数据库模拟session
from rest_framework.views import APIView import hashlib, time from app01 import models from django.core.exceptions import ObjectDoesNotExist from django.http import JsonResponse def get_token(name): ''' 将当前时间戳转化为被hash的md5字符串 - 注意:md5.update(内部必须插入bytes格式) :param name: :return: ''' md5 = hashlib.md5() md5.update(str(time.time()).encode('utf-8')) md5.update(name.encode('utf-8')) return md5.hexdig