Django DRF认证组件流程实现原理详解

2020/08/25 16:08 · python教程 ·  原创文章 · 26阅读 · 0评论

视图函数中加上认证功能,流程见下图

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)
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):函数中找到认证功能

您可能感兴趣的文章

本文地址:http://www.pythongcs.cn/878.html
文章标签:
版权声明:本文为原创文章,版权归 yubaba 所有,欢迎分享本文,转载请保留出处!

文件下载

老薛主机终身7折优惠码boke112

上一篇:
下一篇:

 发表评论


表情