• rest_framework 认证系统


    def get_random_str(user):
        import hashlib,time
        ctime=str(time.time())
    
        md5=hashlib.md5(bytes(user,encoding="utf8"))
        md5.update(bytes(ctime,encoding="utf8"))
    
        return md5.hexdigest()
    
    
    class Login2(APIView):
        # def get(self, request):
        #     return render(request, 'login2.html')
    
        def post(self, request):
    
            res = {'code':1000,'msg':None}
            try:
                user = request.data.get('user')
                pwd = request.data.get('pwd')
                user_obj = User.objects.filter(user=user,pwd=pwd).first()
                print(user,pwd,user_obj)
                if not user_obj:
                    res['code'] = 1001
                    res['msg'] = '用户名或密码错误'
                else:
                    token = get_random_str(user)
                    UserToken.objects.update_or_create(user=user_obj, defaults={"token": token})
                    res['token'] = token
    
            except Exception as e:
                res['code'] = 1002
                res['msg'] = str(e)
    
            return JsonResponse(res, json_dumps_params={"ensure_ascii": False})

    上面的认证系统是根据源码自己写的逻辑 

    下面我们就先来看看源码

    from app01.models import UserToken
    
    from rest_framework.exceptions import AuthenticationFailed
    
    from rest_framework.authentication import BaseAuthentication
    
    class TokeAuth(BaseAuthentication):
    
        def authenticate(self, request):
    
            token = request.GET.get("token", None)
            print(token)
    
            token_obj = UserToken.objects.filter(token=token).first()
            if token_obj:
                return token_obj.user.user,token_obj
            else:
                raise AuthenticationFailed('认证失败!')

    以上就是rest_framework提供的 认证 

     

  • 相关阅读:
    element表格添加序号
    ZOJ 3822 Domination(概率dp)
    HDU 3037(Lucas定理)
    HDU 5033 Building(单调栈维护凸包)
    HDU 5037 Frog(贪心)
    HDU 5040 Instrusive(BFS+优先队列)
    HDU 5120 Intersection(几何模板题)
    HDU 5115 Dire Wolf(区间dp)
    HDU 5119 Happy Matt Friends(dp+位运算)
    C++ string详解
  • 原文地址:https://www.cnblogs.com/yftzw/p/9417922.html
Copyright © 2020-2023  润新知