• Restframework 认证authentication 组件实例-1


    1. 创建用户表和 token表

    class User(models.Model):
        user =models.CharField(max_length=32)
        pwd =models.CharField(max_length=32)
        type=((1,"VIP"),(2,"SVIP"),(1,"SSVIP"))
        user_type = models.IntegerField(choices=type)
    
    
    class UserToken(models.Model):
        user= models.OneToOneField("User")
        token =models.CharField(max_length=128)

    2.创建登录类

    from app01.models import User,UserToken
    
    class LoginView(APIView):
        """
        1000:成功
        1001: 用户名和密码错误
        1002:异常错误
        """
        def post(self,request):
            response = {"code": 100, "msg": None, "user": None}
            try:
                print(request.data)
                user= request.data.get("user")
                pwd =request.data.get("pwd")
    
                user =User.objects.filter(user=user,pwd=pwd).first()
    
                import uuid
                random_str =uuid.uuid4()
    
                if user:
                    response["user"] =user.user
                    UserToken.objects.update_or_create(user =user,defaults={"token":random_str})
                    response["user"] =user.user
                    response["token"] =random_str
                else:
                    response["code"]=1001
                    response["msg"]="密码错误"
    
            except Exception as e:
                 response["code"] =1002
                 response["msg"] =str(e)
    
            return Response(response)
    

    3.设置认证类逻辑.

    from app01.models import UserToken
    from rest_framework.exceptions import AuthenticationFailed
    
    from rest_framework.authentication import BaseAuthentication
    
    class UserAuth(BaseAuthentication):
    
        msg = "认证失败"
        def authenticate(self, request):
            token = request.query_params.get("token")
            usertoken= UserToken.objects.filter(token =token).first()
    
            if usertoken:
                return  usertoken.user, usertoken.token
            else:
                raise  AuthenticationFailed("认证失败!")
    

     

    4.1 应用局部认证 

    class BookView(APIView):
        authentication_classes = [UserAuth]
    
        def get(self,request):
            """
            查看所有书籍
            :param request:
            :return:
            """
            book_list=Book.objects.all()
            serializer= BookSerializer(book_list,many=True)
            return Response(serializer.data)
    
        def post(self,request):
            """
            添加一条书籍
            :param request:
            :return:
            """
            serializer=BookSerializer(data=request.data,many=True)
            if serializer.is_valid():
                serializer.save()#create操作.
                return Response(serializer.data)
            else:
                return Response(serializer.errors)
    

      

    4.2 设置全局认证模式 

    REST_FRAMEWORK={
    
    'DEFAULT_AUTHENTICATION_CLASSES': (
      'app01.utils.auth_class.UserAuth',
    ),
    
    }

    验证.

     

  • 相关阅读:
    正则表达式
    python 多线程编程之threading模块(Thread类)创建线程的三种方法
    python 多线程编程之_thread模块
    python 多线程编程之使用进程和全局解释器锁GIL
    python 多线程编程之进程和线程基础概念
    python操作文件——序列化pickling和JSON
    python操作文件和目录查看、创建、删除、复制
    python同步IO编程——StringIO、BytesIO和stream position
    python同步IO编程——基本概念和文件的读写
    python单元测试unittest、setUp、tearDown()
  • 原文地址:https://www.cnblogs.com/mengbin0546/p/9682125.html
Copyright © 2020-2023  润新知