zoukankan      html  css  js  c++  java
  • DRF认证组件流程分析

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

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

    流程总结:

    • 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返回两个值,流程结束。
  • 相关阅读:
    hdu-1142(记忆化搜索+dij)
    hdu-1140(求距离,精度判断)
    hdu-1131(卡特兰数+大数)
    hdu-1130(卡特兰数+大数乘法,除法模板)
    hdu-1129(模拟题)
    hdu-1128(数学问题,筛数)
    hdu-1124(数学问题,求n!的尾零的个数)
    hdu-1115(计算多边形重心)
    hdu-1121(差分法--数学问题)
    表达式求值(堆栈)
  • 原文地址:https://www.cnblogs.com/wanlei/p/10426844.html
Copyright © 2011-2022 走看看