Django Rest Framework 认证组件
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
'''用户认证章节''' # 用户认证章节:写一个数据接口 from django.http import JsonResponse from .utils import get_token from rest_framework.exceptions import APIException class UserView(APIView): def post(self, request): # 定义返回消息体 response = dict() # 定义需要的用户信息 fields = {"username", "password"} # 定义一个用户信息字典 user_info = dict() if fields.issubset(set(request.data.keys())): # username = request.data.get("username") # password = request.data.get("password") for key in fields: user_info[key] = request.data[key] user_instance = models.UserInfo.objects.filter(**user_info).first() if user_instance is not None: access_token = get_token.genertate_token() models.UserToken.objects.update_or_create(user=user_instance, defaults={ 'token': access_token }) response["status_code"] = 200 response["status_message"] = "登录成功" response["access_token"] = access_token response["user_role"] = user_instance.get_usertype_id_display() else: response["status_code"] = 201 response["status_message"] = "登录失败,用户名或密码错误" return JsonResponse(response) # 定义一个认证类 class UserAuth(): def authenticate_header(self): pass def authenticate(self, request): user_token = request.query_params.get("token") try: #获取token token = models.UserToken.objects.get(token=user_token) return token.user.username,token.token except Exception: raise APIException("没有认证") from rest_framework.viewsets import ModelViewSet class BookView(ModelViewSet): # 在需要认证的数据接口里面指定认证类 authentication_classes = [UserAuth] queryset = models.Book.objects.all() serializer_class = BookSerizlizer
import uuid #创建随机字符串用作token def genertate_token(): res = str(uuid.uuid4()).replace('-','') return res
re_path(r'user/$',views.UserView.as_view()),
全局组件:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'books.authentication_classes.UserAuth' ], }
在项目应用目录下新建一个authentication_classes.py文件.把views.py里面的定义认证类转移过来。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
from rest_framework.exceptions import APIException #导入BaseAuthentication类 from rest_framework.authentication import BaseAuthentication from . import models # 定义一个认证类 class UserAuth(BaseAuthentication): def authenticate_header(self): pass def authenticate(self, request): user_token = request.query_params.get("token") try: #获取token token = models.UserToken.objects.get(token=user_token) return token.user,token.token except Exception: raise APIException("没有认证")